1//////////////////////////////////////////////////////////////////////
   2// LibFile: screws.scad
   3//   Functions and modules for creating metric (ISO) and English (UTS) standard screws and nuts.
   4//   Included is a function for calculating the standard dimensions of screws including the
   5//   tolerance values that are required to make screws mate properly when they are formed
   6//   precisely.  If you can fabricate objects accurately then the modeled screws will mate
   7//   with standard hardware without the need to introduce extra gaps for clearance.
   8// Includes:
   9//   include <BOSL2/std.scad>
  10//   include <BOSL2/screws.scad>
  11// FileGroup: Threaded Parts
  12// FileSummary: ISO (metric) and UTS screws and nuts.
  13//////////////////////////////////////////////////////////////////////
  14
  15include <structs.scad>
  16include <threading.scad>
  17include <screw_drive.scad>
  18
  19// Section: Screw and Nut Parameters
  20//    This modules in this file create standard ISO (metric) and UTS (English) threaded screws.
  21//    The {{screw()}} and {{nut()}} modules produce
  22//    screws and nuts that comply with the relevant ISO and ASME standards,
  23//    including tolerances for screw fit.  You can also create screws with
  24//    various head types and drive types that should match standard hardware.
  25// Subsection: Screw Naming
  26//    You can specify screws using a string that specifies the screw.
  27//    Metric or ISO screws are specified by a diameter in millimeters and a thread pitch in millimeters.  For example,
  28//    an M8x2 screw has a nominal diameter of 8 mm and a thread pitch of 2 mm.  
  29//    The screw specification for these screws has the form: "M`<size>`x`<pitch>`,`<length>`,
  30//    so "M6x1,10" specifies a 6mm diameter screw with a thread pitch of 1mm and length of 10mm.
  31//    You can omit the pitch or length, e.g. "M6x1", or "M6,10", or just "M6".  If you omit the
  32//    length then you must provide the `length` parameter.  If you omit the pitch, the library
  33//    provides a standard pitch for the specified diameter.
  34//    .
  35//    Imperial or UTS screws are specified by a diameter and the number of threads per inch.
  36//    For large screws, the diameter is simply the nominal diameter in inches, so a 5/16-18 screw
  37//    has a nominal diameter of 5/16 inches and 18 threads per inch.  For diameters smaller than
  38//    1/4 inch, the screw diameter is given using a screw gauge, which can be from 0 up to 12.
  39//    A common smaller size is #8-32, an 8 gauge screw with 32 threads per inch.  
  40//    For UTS screws the specification has the form `<size>`-`<threadcount>`,`<length>`, e.g. 
  41//    "#8-32,1/2", or "1/4-20,1".  The units are in inches, including the length.  Size can be a
  42//    gauge number from 0 to 12 with or without a leading # to specify a screw gauge size, or any other
  43//    value to specify a diameter in inches, either as a float or a fraction, so "0.5-13" and
  44//    "1/2-13" are equivalent.  To force interpretation of the value as inches add '' (two
  45//    single-quotes) to the end, e.g. "1''-4" is a one inch screw and "1-80" is a very small
  46//    1-gauge screw.  The pitch is specified using a thread count, the number of threads per inch.
  47//    As with the ISO screws, you can omit the pitch or length and specify "#6-32", "#6,3/4", or simply #6.
  48//    As in the metric case, if you omit the length then you must provide the `length` parameter.  If you omit the pitch, the
  49//    library provides a standard pitch for the specified diameter.
  50// Subsection: Standard Screw Pitch
  51//    If you omit the pitch when specifying a screw or nut then the library supplies a standard screw pitch based
  52//    on the screw diameter as listed in ISO 724 or ASME B1.1.  For many diameters, multiple standard pitches exist.
  53//    The available thread pitch types are different for ISO and UTS:
  54//    .
  55//    | ISO      |    UTS   |
  56//    | -------- | -------- |
  57//    | "coarse" |  "coarse" or "UNC" |
  58//    | "fine"   |   "fine" or "UNF"  |
  59//    | "extrafine" or "extra fine" | "extrafine", "extra fine", or "UNEF"  |
  60//    | "superfine" or "super fine" |   |
  61//    | "none"   |  "none"  |
  62//    .
  63//    The default pitch selection is "coarse".  Note that this selection is case insensitive.
  64//    To set the pitch using these pitch strings you use the `thread=` argument to the modules.
  65//    You cannot incorporate a named pitch into the thread name.  The finer pitch categories
  66//    are defined only for larger screw diameters.  You can also use the `thread=` argument to
  67//    directly specify a pitch, so `thread=2` produces a thread pitch of 2mm.  Setting the
  68//    pitch to zero produces an unthreaded screws, the same as setting it to "none".  Specifying
  69//    a numeric value this way overrides a value given in the specification.  You can also set
  70//    `thread=true` or `thread=false` to turn threading on and off, with the same default coarse
  71//    threading when you set it to true.  
  72// Subsection: Screw Heads
  73//    By default screws do not have heads.  
  74//    You can request a screw head using `head=` parameter to specify the desired head type.  If you want the
  75//    head to have a recess for driving the screw you must also specify a drive type using `drive=`.  
  76//    The table below lists the head options.  Only some combinations of head and drive
  77//    type are supported.  Different sized flat heads exist for the same screw type.
  78//    Sometimes this depends on the type of recess.  If you specify "flat" then the size will be chosen
  79//    appropriately for the recess you specify.
  80//    .
  81//    The `drive=` argument can be set to "none", "hex", "slot", 
  82//    "phillips", "ph0" to "ph4" (for phillips of the specified size), "torx" or
  83//    "t<size>" (for Torx at a specified size, e.g. "t20").  If you have no head but still
  84//    give a drive type you will get a set screw.  The table below lists all of the head types and
  85//    shows which drive type is compatible with each head types.  Different head types work in ISO and UTS,
  86//    as marked in the first column.  
  87//    .
  88//    |ISO|UTS|Head            | Drive  |
  89//    |---|---|--------------- | ----------------------------|
  90//    |X|X|"none"          | hex, torx, slot |
  91//    |X|X|"hex"           | *none*|
  92//    |X|X|"socket"        | hex, torx|
  93//    |X|X|"button"        | hex, torx|
  94//    |X|X|"flat"          | slot, phillips, hex, torx|
  95//    |X|X|"flat sharp"    | slot, phillips, hex, torx|
  96//    | |X|"flat small"    | slot, phillips|
  97//    | |X|"flat large"    | hex, torx |
  98//    | |X|"flat undercut" | slot, phillips |
  99//    | |X|"flat 82"       | slot, phillips |
 100//    | |X|"flat 100"      | slot, phillips |
 101//    | |X|"round"         | slot, phillips |
 102//    | |X|"fillister"     | slot, phillips |
 103//    |X|X|"pan"           | slot, phillips, torx (ISO only) |
 104//    |X| |"cheese"        | slot, phillips, torx |
 105//    .
 106//    The drive size is specified appropriately for the drive type: drive number for phillips or torx,
 107//    and recess width in mm or inches (as appropriate) for hex.  Drive size is determined automatically
 108//    from the screw size, but by passing the `drive_size=` argument you can override the default, or
 109//    in cases where no default exists you can specify it.  Flat head screws have variations such as 100 degree
 110//    angle for UTS, or undercut heads.  You can also request a "sharp" screw which will set the screw diameter 
 111//    the theoretical maximum and produce sharp corners instead of a flat edge on the head.  For a flat head screw
 112//    the drive specification must start with "flat", but the flat head options
 113//    can be mixed in any order, for example, "flat sharp undercut" or "flat undercut sharp".
 114// Subsection: Nuts
 115//    Nuts come in standard sizes and BOSL2 has tables to produce sizes for both Imperial and metric nuts.
 116//    A nut for a given thread size is defined by its shape, width and thickness.  The shape is either "hex"
 117//    for hexagonal nuts or "square" for square nuts.  For hexagonal Imperial nuts, you can choose from thickness values
 118//    of "thin", "normal" or "thick", but the thin and thick nuts are defined only for thread sizes of 1/4 inch and above.
 119//    .
 120//    Metric nut standards are more complicated because ISO has a series of standards and DIN has a series of conflicting
 121//    standards.  Nuts from McMaster-Carr in the USA comply with DIN rather than ISO.  Furthermore, ISO does not appear
 122//    to specify dimensions for square nuts.  For metric nuts you can specify "thin", "normal" and "thick" and the
 123//    nut will be constructed to ISO standards (ISO 4035, ISO 4032, and ISO 4033 respectively).  The DIN standard for thin
 124//    nuts matches ISO, but the DIN normal thickness nuts are thinner than ISO nuts.  You can request DIN nuts
 125//    by specifying a thickness of "DIN" or "undersized".  If you request a square nut it necessariliy derives from DIN
 126//    instead of ISO.  For most nut sizes, the nut widths match between ISO and DIN, but they do differ for M10, M12, M14 and M22.
 127//    .
 128//    You can of course specify nuts by giving an explicit numerical width and thickness in millimeters. 
 129// Subsection: Tolerance
 130//    Without tolerance requirements, screws would not fit together.  The screw standards specify a
 131//    nominal size, but the tolerance determines a range of allowed sizes based on that nominal size.
 132//    So for example, an M10 screw with the default tolerance has an outside (major) diameter between 9.74 mm and 9.97 mm.
 133//    The library will use the center point in the allowed range and create a screw with a diameter of 9.86 mm.
 134//    A M10 nut at the default tolerance has a major diameter (which is the inside diameter) between 10 mm and 10.4 mm.
 135//    Shrinking the major diameter of a screw makes the screw loose.  Shrinking the major diameter of a nut, on the other hand,
 136//    makes the hole smaller and hence makes the nut tighter.  For this reason, we need a difference tolerance
 137//    for a screw than for a nut.  Screw tolerances shrink the diameter to make the screw looser whereas nut tolerances
 138//    increase the diameter to make the nut looser.  Screws modeled using this library will have dimensions consistent with the
 139//    standards they are based on, so that they will interface properly if fabricated by an accurate method.  The ISO and UTS
 140//    systems use different tolerance designations.
 141//    .
 142//    For UTS screw threads the tolerance is one of "1A", "2A" or "3A", in
 143//    order of increasing tightness.  The default tolerance is "2A", which
 144//    is the general standard for manufactured bolts.
 145//    .
 146//    For UTS nut threads, the tolerance is one of "1B", "2B" or "3B", in
 147//    order of increasing tightness.  The default tolerance is "2B", which
 148//    is the general standard for manufactured nuts.
 149//    .
 150//    The ISO tolerances are more complicated.  For both screws and nuts the ISO tolerance has the form of a number
 151//    and letter.  The letter specifies the "fundamental deviation", also called the "tolerance position", the gap
 152//    from the nominal size.  The number specifies the allowed range (variability) of the thread heights.  For
 153//    screws, the letter must be "e", "f", "g", or "h", where "e" is the loosest and "h" means no gap.  The number
 154//    for a screw tolerance must be a value from 3-9 for crest diameter and one of 4, 6, or 8 for pitch diameter.
 155//    A tolerance "6g" specifies both pitch and crest diameter to be the same, but they can be different, with a
 156//    tolerance like "5g6g" specifies a pitch diameter tolerance of "5g" and a crest diameter tolerance of "6g".
 157//    Smaller numbers give a tighter tolerance.  The default ISO screw tolerance is "6g".
 158//    .
 159//    For ISO nuts the letters specifying the fundamental deviation are upper case and must be "G" or "H" where "G"
 160//    is loose and "H" means no gap. The number specifying the variability must range from 4-8.  An allowed (loose)
 161//    nut tolerance is "7G".  The default ISO tolerance is "6H".
 162//    .
 163//    Clearance holes have a different tolerance system, described in {{screw_hole()}}.
 164//    .
 165//    If you wish to create screws at the nominal size you can set the tolerance to 0 or "none".  
 166// Subsection: screw_info and nut_info structures
 167//    When you make a screw or nut, information about the object such as the thread characteristics 
 168//    head and drive size, or nut thickness are placed into a data structure.  The screw and nut 
 169//    modules can accept screw names, as described above, or they can accept screw structures. 
 170//    When you use a screw structure as a specification, computed values like head type and size and
 171//    driver characteristics are fixed and cannot be changed, but values that are not computed
 172//    like length can still be altered.  If you want to create an unusual part you can hand
 173//    generate the structure with your desired parameters to fill in values that would normally
 174//    be produced automatically from the standard tables.  So if your hardware is missing from the
 175//    tables, or is sized differently, you can still create the part.  For details on the
 176//    screw_info and nut_info structures, see {{screw_info()}} and {{nut_info()}}.  
 177//    .
 178//    All of the screw related modules set the variable `$screw_spec` to contain the specification
 179//    for their screw.  This means that child modules can make use of this variable to create
 180//    mating (or identical) parts.  Note that the `shaft_oversize` and `head_oversize` screw
 181//    info fields are only inherited into modules that are the same as the parent module.
 182//    This means that if you create an oversized screw hole and then make a screw as s child, the
 183//    child screw will **not** inherit the oversize parameters.  But a screw_hole will inherit 
 184//    oversize parameters from a parent screw_hole.  
 185
 186/*
 187http://mdmetric.com/thddata.htm#idx
 188
 189Seems to show JIS has same nominal thread as others
 190https://www.nbk1560.com/~/media/Images/en/Product%20Site/en_technical/11_ISO%20General%20Purpose%20Metric%20Screw%20Threads.ashx?la=en
 191
 192Various ISO standards here:  https://www.fasteners.eu/standards/ISO/4026/
 193
 194Torx values:  https://www.stanleyengineeredfastening.com/-/media/web/sef/resources/docs/other/socket_screw_tech_manual_1.ashx
 195
 196*/
 197
 198
 199// Section: Making Screws
 200
 201// Module: screw()
 202// Synopsis: Creates a standard screw with optional tolerances.
 203// SynTags: Geom
 204// Topics: Threading, Screws
 205// See Also: screw_hole(), shoulder_screw()
 206// Usage:
 207//   screw([spec], [head], [drive], [thread=], [drive_size=], [length=|l=], [thread_len=], [undersize=], [shaft_undersize=], [head_undersize=], [tolerance=], [blunt_start=], [details=], [anchor=], [atype=], [orient=], [spin=]) [ATTACHMENTS];
 208// Description:
 209//   Create a screw.  See [screw and nut parameters](#section-screw-and-nut-parameters) for details on
 210//   the parameters that define a screw.  The tolerance determines the dimensions of the screw based
 211//   on ISO and ASME standards.  Screws fabricated at those dimensions will mate properly with
 212//   standard hardware.  Note that the $slop argument does not affect the size of screws: it only
 213//   adjusts screw holes.  This will work fine if you are printing both parts, but if you need to mate
 214//   printed screws to metal parts you may need to adjust the size of the screws, which you can do
 215//   with the undersize arguments.
 216//   .
 217//   You can generate a screw specification from {{screw_info()}}, possibly create a modified version
 218//   using {{struct_set()}}, and pass that in rather than giving the parameters.
 219//   .
 220//   Various anchor types refer to different parts of the screw, some of which are labeled below.  The
 221//   "screw" anchor type (the default) is simply the entire screw, so TOP and BOTTOM refer to the head
 222//   end and tip respectively, and CENTER is the midpoint of the whole screw, including the head.  The
 223//   "head" anchor refers to the head alone.  Both of these anchor types refer to the bounding
 224//   cylinder for the specified screw part, except for hex heads, which anchor to a hexagonal prism.
 225// Figure(2D,Med,VPD = 140, VPT = [18.4209, 14.9821, -3.59741], VPR = [0, 0, 0],NoAxes):
 226//   rpos=33;
 227//   fsize=2.5;
 228//   projection(cut=true) xrot(-90)screw("M8", head="socket", length=25, thread_len=10,anchor=BOT);
 229//   right(rpos)projection(cut=true) xrot(-90)screw("M8", head="flat", length=25, thread_len=10,anchor=BOT);
 230//   color("black"){
 231//      stroke([[5,0],[5,10]],endcaps="arrow2",width=.3);
 232//      back(5)right(6)text("threads",size=fsize,anchor=LEFT);
 233//      stroke([[5,10],[5,25]],endcaps="arrow2",width=.3);
 234//      back(10+15/2)right(6)text("shank",size=fsize,anchor=LEFT);
 235//      stroke([[-5,0],[-5,25]],endcaps="arrow2",width=.3);
 236//      back(25/2)right(-6)text("shaft",size=fsize,anchor=RIGHT);
 237//   }
 238//   sh=10.2841;
 239//   right(rpos)
 240//   color("black"){
 241//      stroke([[5,0],[5,10]],endcaps="arrow2",width=.3);
 242//      back(5)right(6)text("threads",size=fsize,anchor=LEFT);
 243//      stroke([[5,10],[5,10+sh]],endcaps="arrow2",width=.3);
 244//      back(10+sh/2)right(6)text("shank",size=fsize,anchor=LEFT);
 245//      stroke([[-5,0],[-5,10+sh]],endcaps="arrow2",width=.3);
 246//      back((10+sh)/2)right(-6)text("shaft",size=fsize,anchor=RIGHT);
 247//   }
 248// Arguments:
 249//   spec = screw specification, e.g. "M5x1" or "#8-32".  See [screw naming](#subsection-screw-naming).  This can also be a screw specification structure of the form produced by {{screw_info()}}.  
 250//   head = head type.  See [screw heads](#subsection-screw-heads)  Default: none
 251//   drive = drive type.  See [screw heads](#subsection-screw-heads) Default: none
 252//   ---
 253//   length / l = length of screw (in mm)
 254//   thread = thread type or specification. See [screw pitch](#subsection-standard-screw-pitch). Default: "coarse"
 255//   drive_size = size of drive recess to override computed value
 256//   thread_len = length of threaded portion of screw (in mm), for making partly threaded screws.  Default: fully threaded
 257//   details = toggle some details in rendering.  Default: true
 258//   tolerance = screw tolerance.  Determines actual screw thread geometry based on nominal sizing.  See [tolerance](#subsection-tolerance). Default is "2A" for UTS and "6g" for ISO.  
 259//   undersize = amount to decrease screw diameter, a scalar to apply to all parts, or a 2-vector to control shaft and head.  Replaces rather than adding to the head_oversize value in a screw specification.  
 260//   shaft_undersize = amount to decrease diameter of the shaft of screw; replaces rather than adding to the shaft_oversize value in a screw specification. 
 261//   head_undersize = amount to decrease the head diameter of the screw; replaces rather than adding to the head_oversize value in a screw specification. 
 262//   bevel1 = bevel bottom end of screw.  Default: true
 263//   bevel2 = bevel top end of threaded section.  Default: true for fully threaded or unthreaded headless, false otherwise
 264//   bevel = bevel both ends of the threaded section.
 265//   blunt_start = if true and hole is threaded, create blunt start threads.  Default: true
 266//   blunt_start1 = if true and hole is threaded, create blunt start threads at bottom end.
 267//   blunt_start2 = if true and hole is threaded, create blunt start threads top end.
 268//   atype = anchor type, one of "screw", "head", "shaft", "threads", "shank"
 269//   anchor = Translate so anchor point on the shaft is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `CENTER`
 270//   spin = Rotate this many degrees around the Z axis after anchor.  See [spin](attachments.scad#subsection-spin).  Default: `0`
 271//   orient = Vector to rotate top towards, after spin.  See [orient](attachments.scad#subsection-orient).  Default: `UP`
 272// Side Effects:
 273//   `$screw_spec` is set to the spec specification structure. 
 274// Anchor Types:
 275//   screw = the entire screw (default)
 276//   head = screw head (invalid for headless screws)
 277//   shaft = screw shaft
 278//   shank = unthreaded section of shaft (invalid if screw is fully threaded)
 279//   threads = threaded section of screw     
 280// Named Anchors:
 281//   "top" = top of screw
 282//   "bot" = bottom of screw
 283//   "center" = center of screw
 284//   "head_top" = top of head (same as top for headless screws)
 285//   "head_bot" = bottom of head (same as top for headless screws)
 286//   "head_center" = center of head (same as top for headless screws)
 287//   "shaft_top" = top of shaft
 288//   "shaft_bot" = bottom of shaft
 289//   "shaft_center" = center of shaft
 290//   "shank_top" = top of shank (invalid if screw is fully threaded)
 291//   "shank_bot" = bottom of shank (invalid if screw is fully threaded)
 292//   "shank_center" = center of shank (invalid if screw is fully threaded)
 293//   "threads_top" = top of threaded portion of screw (invalid if thread_len=0)
 294//   "threads_bot" = bottom of threaded portion of screw (invalid if thread_len=0)
 295//   "threads_center" = center of threaded portion of screw (invalid if thread_len=0)
 296// Example(Med): Selected UTS (English) screws
 297//   $fn=32;
 298//   xdistribute(spacing=8){
 299//     screw("#6", length=12);
 300//     screw("#6-32", head="button", drive="torx",length=12);
 301//     screw("#6-32,3/4", head="hex");
 302//     screw("#6", thread="fine", head="fillister",length=12, drive="phillips");
 303//     screw("#6", head="flat small",length=12,drive="slot");
 304//     screw("#6-32", head="flat large", length=12, drive="torx");
 305//     screw("#6-32", head="flat undercut",length=12);
 306//     screw("#6-24", head="socket",length=12);          // Non-standard threading
 307//     screw("#6-32", drive="hex", drive_size=1.5, length=12);
 308//   }
 309// Example(Med): A few examples of ISO (metric) screws
 310//   $fn=32;
 311//   xdistribute(spacing=8){
 312//     screw("M3", head="flat small",length=12);
 313//     screw("M3", head="button",drive="torx",length=12);
 314//     screw("M3", head="pan", drive="phillips",length=12);
 315//     screw("M3x1", head="pan", drive="slot",length=12);   // Non-standard threading!
 316//     screw("M3", head="flat large",length=12);
 317//     screw("M3", thread="none", head="flat", drive="hex",length=12);  // No threads
 318//     screw("M3", head="socket",length=12);
 319//     screw("M5,18", head="hex");
 320//   }
 321// Example(Med): Demonstration of all head types for UTS screws (using pitch zero for fast preview)
 322//   xdistribute(spacing=15){
 323//     ydistribute(spacing=15){
 324//        screw("1/4", thread=0,length=8, anchor=TOP, head="none", drive="hex");
 325//        screw("1/4", thread=0,length=8, anchor=TOP, head="none", drive="torx");
 326//        screw("1/4", thread=0,length=8, anchor=TOP, head="none", drive="slot");
 327//        screw("1/4", thread=0,length=8, anchor=TOP, head="none");
 328//     }
 329//     screw("1/4", thread=0, length=8, anchor=TOP, head="hex");
 330//     ydistribute(spacing=15){
 331//        screw("1/4", thread=0,length=8, anchor=TOP, head="socket", drive="hex");
 332//        screw("1/4", thread=0,length=8, anchor=TOP, head="socket", drive="torx");
 333//        screw("1/4", thread=0,length=8, anchor=TOP, head="socket");
 334//     }
 335//     ydistribute(spacing=15){
 336//        screw("1/4", thread=0,length=8, anchor=TOP, head="socket ribbed", drive="hex",$fn=32);
 337//        screw("1/4", thread=0,length=8, anchor=TOP, head="socket ribbed", drive="torx",$fn=32);
 338//        screw("1/4", thread=0,length=8, anchor=TOP, head="socket ribbed",$fn=24);
 339//     }
 340//     ydistribute(spacing=15){
 341//        screw("1/4", thread=0,length=8, anchor=TOP, head="button", drive="hex");
 342//        screw("1/4", thread=0,length=8, anchor=TOP, head="button", drive="torx");
 343//        screw("1/4", thread=0,length=8, anchor=TOP, head="button");
 344//     }
 345//     ydistribute(spacing=15){
 346//        screw("1/4", thread=0,length=8, anchor=TOP, head="round", drive="slot");
 347//        screw("1/4", thread=0,length=8, anchor=TOP, head="round", drive="phillips");
 348//        screw("1/4", thread=0,length=8, anchor=TOP, head="round");
 349//     }     
 350//     ydistribute(spacing=15){
 351//        screw("1/4", thread=0,length=8, anchor=TOP, head="pan", drive="slot");
 352//        screw("1/4", thread=0,length=8, anchor=TOP, head="pan", drive="phillips");
 353//        screw("1/4", thread=0,length=8, anchor=TOP, head="pan");
 354//     }
 355//     ydistribute(spacing=15){
 356//        screw("1/4", thread=0,length=8, anchor=TOP, head="fillister", drive="slot");
 357//        screw("1/4", thread=0,length=8, anchor=TOP, head="fillister", drive="phillips");
 358//        screw("1/4", thread=0,length=8, anchor=TOP, head="fillister");
 359//     }
 360//     ydistribute(spacing=15){
 361//        screw("1/4", thread=0,length=8, anchor=TOP, head="flat", drive="slot");
 362//        screw("1/4", thread=0,length=8, anchor=TOP, head="flat", drive="phillips");
 363//        screw("1/4", thread=0,length=8, anchor=TOP, head="flat", drive="hex");
 364//        screw("1/4", thread=0,length=8, anchor=TOP, head="flat", drive="torx");
 365//        screw("1/4", thread=0,length=8, anchor=TOP, head="flat large");
 366//        screw("1/4", thread=0,length=8, anchor=TOP, head="flat small");
 367//     }
 368//     ydistribute(spacing=15){
 369//        screw("1/4", thread=0,length=8, anchor=TOP, head="flat undercut", drive="slot");
 370//        screw("1/4", thread=0,length=8, anchor=TOP, head="flat undercut", drive="phillips");
 371//        screw("1/4", thread=0,length=8, anchor=TOP, head="flat undercut");
 372//     }
 373//     ydistribute(spacing=15){
 374//        screw("1/4", thread=0,length=8, anchor=TOP, head="flat 100", drive="slot");
 375//        screw("1/4", thread=0,length=8, anchor=TOP, head="flat 100", drive="phillips");
 376//        screw("1/4", thread=0,length=8, anchor=TOP, head="flat 100");
 377//     }
 378//   }
 379// Example(Med): Demonstration of all head types for metric screws without threading.
 380//   xdistribute(spacing=15){
 381//     ydistribute(spacing=15){
 382//       screw("M6x0", length=8, anchor=TOP,  head="none", drive="hex");
 383//       screw("M6x0", length=8, anchor=TOP,  head="none", drive="torx");
 384//       screw("M6x0", length=8, anchor=TOP,  head="none", drive="slot");
 385//       screw("M6x0", length=8, anchor=TOP);
 386//     }
 387//     screw("M6x0", length=8, anchor=TOP,  head="hex");
 388//     ydistribute(spacing=15){
 389//       screw("M6x0", length=8, anchor=TOP,  head="socket", drive="hex");
 390//       screw("M6x0", length=8, anchor=TOP,  head="socket", drive="torx");
 391//       screw("M6x0", length=8, anchor=TOP,  head="socket");
 392//     }
 393//     ydistribute(spacing=15){
 394//       screw("M6x0", length=8, anchor=TOP,  head="socket ribbed", drive="hex", $fn=32);
 395//       screw("M6x0", length=8, anchor=TOP,  head="socket ribbed", drive="torx", $fn=32);
 396//       screw("M6x0", length=8, anchor=TOP,  head="socket ribbed", $fn=32);
 397//     }
 398//     ydistribute(spacing=15){
 399//       screw("M6x0", length=8, anchor=TOP,  head="pan", drive="slot");
 400//       screw("M6x0", length=8, anchor=TOP,  head="pan", drive="phillips");
 401//       screw("M6x0", length=8, anchor=TOP,  head="pan", drive="torx");
 402//       screw("M6x0", length=8, anchor=TOP,  head="pan");
 403//       screw("M6x0", length=8, anchor=TOP,  head="pan flat");
 404//     }
 405//     ydistribute(spacing=15){
 406//       screw("M6x0", length=8, anchor=TOP,  head="button", drive="hex");
 407//       screw("M6x0", length=8, anchor=TOP,  head="button", drive="torx");
 408//       screw("M6x0", length=8, anchor=TOP,  head="button");
 409//     }
 410//     ydistribute(spacing=15){
 411//       screw("M6x0", length=8, anchor=TOP,  head="cheese", drive="slot");
 412//       screw("M6x0", length=8, anchor=TOP,  head="cheese", drive="phillips");
 413//       screw("M6x0", length=8, anchor=TOP,  head="cheese", drive="torx");
 414//       screw("M6x0", length=8, anchor=TOP,  head="cheese");
 415//     }
 416//     ydistribute(spacing=15){
 417//       screw("M6x0", length=8, anchor=TOP,  head="flat", drive="phillips");
 418//       screw("M6x0", length=8, anchor=TOP,  head="flat", drive="slot");
 419//       screw("M6x0", length=8, anchor=TOP,  head="flat", drive="hex");
 420//       screw("M6x0", length=8, anchor=TOP,  head="flat", drive="torx");
 421//       screw("M6x0", length=8, anchor=TOP,  head="flat small");
 422//       screw("M6x0", length=8, anchor=TOP,  head="flat large");
 423//     }
 424//   }
 425// Example: The three different English (UTS) screw tolerances (labeled on their heads)
 426//   module label(val)
 427//   {
 428//     difference(){
 429//        children();
 430//        yflip()linear_extrude(height=.35) text(val,valign="center",halign="center",size=8);
 431//     }
 432//   }
 433//   $fn=64;
 434//   xdistribute(spacing=15){
 435//     label("1") screw("1/4-20,5/8", head="hex",orient=DOWN,atype="head", anchor=TOP,tolerance="1A");  // Loose
 436//     label("2") screw("1/4-20,5/8", head="hex",orient=DOWN,atype="head", anchor=TOP,tolerance="2A");  // Standard
 437//     label("3") screw("1/4-20,5/8", head="hex",orient=DOWN,atype="head", anchor=TOP,tolerance="3A");  // Tight
 438//   }
 439// Example(2D,NoAxes): This example shows the gap between nut and bolt at the loosest tolerance for UTS.  This gap is what enables the parts to mesh without binding and is part of the definition for standard metal hardware.  Note that this gap is part of the standard definition for the metal hardware, not the 3D printing adjustment provided by the $slop parameter.  
 440//   $fn=32;
 441//   projection(cut=true)xrot(-90){
 442//       screw("1/4-20,3/8", head="hex",orient=UP,anchor=BOTTOM,tolerance="1A");
 443//       down(INCH*1/20*1.5) nut("1/4-20", thickness=8, nutwidth=0.5*INCH, tolerance="1B");
 444//   }
 445// Example: Here is a screw with nonstandard threading and a weird head size, which we create by modifying the screw structure:
 446//   spec = screw_info("M6x2,12",head="socket");
 447//   newspec = struct_set(spec,["head_size",20,"head_height",3]);
 448//   screw(newspec);
 449// Example: A bizarre custom screw with nothing standard about it.  If your screw is very strange, consider setting tolerance to zero so you get exactly the screw you defined.  You'll need to create your own clearance between mating threads in this case.  
 450//   spec = [["system","ISO"],
 451//           ["type","screw_info"],
 452//           ["pitch", 2.3],
 453//           ["head", "flat"],
 454//           ["head_size", 20],
 455//           ["head_size_sharp", 22],
 456//           ["head_angle", 60],
 457//           ["diameter",12],
 458//           ["length",22]];
 459//   screw(spec,tolerance=0);
 460
 461function _get_spec(spec, needtype, origin, thread,   // common parameters
 462                   head, drive, drive_size,          // screw parameters
 463                   shape, thickness                  // nut parameters
 464                  ) =
 465    assert(needtype=="screw_info" || needtype=="nut_info")
 466    assert(is_undef(thickness) || (is_num(thickness) && thickness>0) ||
 467           in_list(_downcase_if_str(thickness),["thin","normal","thick","undersized","din"]),
 468          "thickness must be a positive number of one of \"thin\", \"thick\", \"normal\", \"undersized\", or \"DIN\"")
 469    assert(!(is_undef(spec) && is_undef($screw_spec)), "No screw spec given and no parent spec available to inherit")
 470    let(
 471        spec=is_undef(spec) ? $screw_spec : spec,
 472        spec_origin = is_struct(spec) ? struct_val(spec,"origin") : undef
 473    )
 474    assert(is_string(spec) || is_struct(spec), "Screw/nut specification must be a string or struct")
 475    let(
 476        specname = is_struct(spec) ? struct_val(spec,"name") : undef,
 477        name = is_string(spec) ? spec
 478             : struct_val(spec,"type") != needtype ?       // if we switch between screw and nut we need a name 
 479                   let(specname=struct_val(spec,"name"))
 480                   assert(is_string(specname), 
 481                        "Parent screw_info or nut_info structure doesn't have a valid name, but a name is needed when child is of a different type")
 482               specname
 483             : undef,
 484        p = is_struct(spec) ? struct_val(spec,"pitch") : undef,
 485        thread = is_def(name) ? thread
 486                 // If the origin of the struct is a hole with pitch zero and we are making a screw, try to find a nonzero pitch
 487               : spec_origin=="screw_hole" && origin!="screw_hole" && p==0 && is_string(specname) ?
 488                    let(temp_info = screw_info(specname,thread))
 489                    struct_val(temp_info,"pitch")
 490//               : spec_origin=="screw_hole" && origin=="screw_hole" && all_positive([p]) ? p
 491//               : origin=="screw_hole" && is_undef(thread) ? 0
 492               : thread
 493    )
 494    is_def(name) ? (needtype=="screw_info" ? screw_info(name,_origin=origin, thread= origin=="screw_hole" ? default(thread,true) : thread,
 495                                                        head=head, drive=drive, drive_size=drive_size)
 496                                           : nut_info(name,_origin=origin, thread=thread, shape=shape, thickness=thickness))
 497  : 
 498    assert(in_list(struct_val(spec,"type"), ["nut_info","screw_info"]), "Screw/nut spec is invalid struct type")
 499    assert(is_undef(thread) || thread=="none" || thread==false || thread==true || is_num(thread),
 500           str("Thread type applied to struct specification must be numeric, \"none\" or false but got ",thread))
 501    assert(is_undef(thickness) || is_num(thickness), str("thickness applied to struct specification must be numeric but is ",thickness))
 502    assert(is_undef(head) || head=="none", str("The only head type allowed with struct specifications is \"none\" but got ",head))
 503    assert(num_defined([drive,drive_size])==0, "You cannot change drive or drive_size when using a struct specification")
 504    assert(is_undef(shape), "You cannot change nut shape when using a struct specification")
 505    let(
 506        spec = _struct_reset(spec,
 507                                   [ 
 508                                     ["origin", origin],
 509                                     if (origin=="screw") ["counterbore",0],
 510                                     if (head=="none") ["head","none"],
 511                                     if (head=="none") ["drive","none"],
 512                                     if (thread==false || thread=="none") ["pitch",0]
 513                                     else if (thread!=true) ["pitch",thread],
 514                                     ["thickness", thickness],
 515                                   ], grow=true),
 516        inherit = is_undef(spec_origin) || spec_origin==origin 
 517    )
 518    inherit ? spec
 519  : struct_remove(spec, ["shaft_oversize","head_oversize"]);
 520
 521
 522function _struct_reset(s, keyval, grow=true) =
 523  let(
 524      good = [for(kv=keyval) (grow || is_def(struct_val(s,kv[0]))) && is_def(kv[1])]
 525  )
 526  struct_set(s,flatten(bselect(keyval,good)));
 527
 528
 529function _nominal_diam(spec) = struct_val(spec,"diameter")+default(struct_val(spec,"shaft_oversize"),0);
 530                                                    
 531function screw(spec, head, drive, thread, drive_size, 
 532             length, l, thread_len, tolerance, details=true, 
 533             undersize, shaft_undersize, head_undersize,
 534             atype="screw",anchor, spin=0, orient=UP,
 535             _shoulder_diam=0, _shoulder_len=0,
 536             bevel,bevel1,bevel2,bevelsize,
 537             blunt_start,blunt_start1, blunt_start2,
 538             _internal=false, _counterbore, _teardrop=false)
 539   = no_function("screw");
 540module screw(spec, head, drive, thread, drive_size, 
 541             length, l, thread_len, tolerance, details=true, 
 542             undersize, shaft_undersize, head_undersize,
 543             atype="screw",anchor, spin=0, orient=UP,
 544             _shoulder_diam=0, _shoulder_len=0,
 545             bevel,bevel1,bevel2,bevelsize,
 546             blunt_start,blunt_start1, blunt_start2,
 547             _internal=false, _counterbore, _teardrop=false)
 548{
 549   tempspec = _get_spec(spec, "screw_info", _internal ? "screw_hole" : "screw",
 550                        thread=thread, head=head, drive=drive, drive_size=drive_size);
 551   undersize = is_num(undersize) ? [undersize,undersize]
 552             : undersize;
 553   dummyA=assert(is_undef(undersize) || is_vector(undersize,2), "Undersize must be a scalar or 2-vector")
 554          assert(is_undef(undersize) || num_defined([shaft_undersize, head_undersize])==0,
 555                 "Cannot combine \"undersize\" with other more specific undersize parameters")
 556          assert(is_bool(_teardrop) ||_teardrop=="max" || all_nonnegative([_teardrop]), str("Invalid teardrop parameter",_teardrop));
 557   _teardrop = _teardrop==true ? .05 : _teardrop;   // set teardrop default
 558   shaft_undersize = first_defined([shaft_undersize, undersize[0]]);
 559   head_undersize = first_defined([head_undersize, undersize[1]]);
 560   dummyB=assert(is_undef(shaft_undersize) || is_finite(shaft_undersize), "shaft_undersize must be a number")
 561          assert(is_undef(head_undersize) || is_finite(head_undersize), "head_undersize must be a number")
 562          assert(is_undef(_counterbore) || is_bool(_counterbore) || (is_finite(_counterbore) && _counterbore>=0),
 563                 "Counterbore must be a nonnegative number of boolean");
 564   l = one_defined([l,length],"l,length",dflt=undef);
 565   _counterbore = _counterbore==true ? struct_val(tempspec,"head_height") 
 566                : _counterbore==false ? undef
 567                : _counterbore;
 568   head = struct_val(tempspec,"head");
 569   headless = head=="none";
 570   flathead = is_def(head) && starts_with(head,"flat");
 571   reset_headsize = _internal && flathead ? struct_val(tempspec,"head_size_sharp") : undef;
 572   spec=_struct_reset(tempspec,[
 573                                ["length", l],
 574                                ["shaft_oversize", u_mul(-1,shaft_undersize)],
 575                                ["head_oversize", u_mul(-1,head_undersize)],
 576                                ["counterbore", _counterbore],
 577                                ["thread_len", thread_len],
 578                                ["head_size", reset_headsize],
 579                               ]);
 580   dummy = _validate_screw_spec(spec);
 581   $screw_spec = spec;
 582   pitch =  struct_val(spec, "pitch") ;
 583   threadspec = pitch==0 ? undef : thread_specification(spec, internal=_internal, tolerance=tolerance);
 584   nominal_diam = _nominal_diam(spec);
 585   d_major = pitch==0 ? nominal_diam : mean(struct_val(threadspec, "d_major"));
 586   length = struct_val(spec,"length");
 587   counterbore = default(struct_val(spec,"counterbore"),0);
 588   user_thread_len = struct_val(spec,"thread_len");
 589   dummyC = assert(in_list(atype,["shaft","head","shank","threads","screw","shoulder"]),str("Unknown anchor type: \"",atype,"\""))
 590            assert(is_finite(length) && length>0, "Must specify positive screw length")
 591            assert(is_finite(_shoulder_len) && _shoulder_len>=0, "Must specify a nonegative shoulder length")
 592            assert(is_finite(_shoulder_diam) && _shoulder_diam>=0, "Must specify nonnegative shoulder diameter")
 593            assert(is_undef(user_thread_len) || (is_finite(user_thread_len) && user_thread_len>=0), "Must specify nonnegative thread length");
 594   sides = max(pitch==0 ? 3 : 12, segs(nominal_diam/2));
 595   head_height = headless || flathead ? 0 
 596               : counterbore==true || is_undef(counterbore) || counterbore==0 ? struct_val(spec, "head_height")
 597               : counterbore;
 598   head_diam = struct_val(spec, "head_size",0) + struct_val(spec, "head_oversize",0);
 599   flat_height = !flathead ? 0 
 600               : let( given_height = struct_val(spec, "head_height"))
 601                 all_positive(given_height) ? given_height
 602               : (struct_val(spec,"head_size_sharp")+struct_val(spec,"head_oversize",0)-d_major)/2/tan(struct_val(spec,"head_angle")/2);
 603   flat_cbore_height = flathead && is_num(counterbore) ? counterbore : 0;
 604
 605   blunt_start1 = first_defined([blunt_start1,blunt_start,true]);
 606   blunt_start2 = first_defined([blunt_start2,blunt_start,true]);
 607
 608   shoulder_adj = _shoulder_len>0 ? flat_height:0;  // Adjustment because flathead height doesn't count toward shoulder length
 609   shoulder_full = _shoulder_len==0 ? 0 : _shoulder_len + flat_height;
 610   shank_len = is_def(user_thread_len) ? length - user_thread_len - (_shoulder_len==0?flat_height:0) : 0;
 611   thread_len = is_def(user_thread_len) ? user_thread_len
 612              : length - (_shoulder_len==0?flat_height:0);
 613   dummyD = assert(!(atype=="shank" && shank_len==0), "Specified atype of \"shank\" but screw has no shank (thread_len not given or it equals shaft length)")
 614            assert(!(atype=="shoulder" && _shoulder_len==0), "Specified atype of \"shoulder\" but screw has no shoulder")
 615            assert(!(atype=="threads" && thread_len==0), "Specified atype of \"threads\" but screw has no threaded part (thread_len=0)")
 616            assert(!(atype=="head" && headless), "You cannot anchor headless screws with atype=\"head\"");
 617   eps_gen = 0.01;
 618   eps_shoulder = headless && !_internal ? 0 : eps_gen;
 619   eps_shank = headless && !_internal && _shoulder_len==0 ? 0 : eps_gen;
 620   eps_thread = headless && !_internal && shank_len==0 && _shoulder_len==0 ? 0 : eps_gen;
 621   dummyL = assert(_shoulder_len>0 || is_undef(flat_height) || flat_height < length,
 622                   str("Length of screw (",length,") is shorter than the flat head height (",flat_height,")"));
 623   offset = atype=="head" ? (-head_height+flat_height-flat_cbore_height)/2
 624          : atype=="shoulder" ? _shoulder_len/2 + flat_height
 625          : atype=="shaft" ? _shoulder_len + (length+flat_height+shoulder_adj)/2
 626          : atype=="shank" ? _shoulder_len + (length-thread_len+flat_height+shoulder_adj)/2
 627          : atype=="threads" ? _shoulder_len + shoulder_adj + length-thread_len + thread_len/2
 628          : atype=="screw" ? (length-head_height+_shoulder_len+shoulder_adj-flat_cbore_height)/2
 629          : assert(false,"Unknown atype");
 630   dummyM = //assert(!headless || !in_list(anchor,["head_top","head_bot","head_center"]), str("Anchor \"",anchor,"\" not allowed for headless screw"))
 631            assert(shank_len>0 || !in_list(anchor,["shank_top","shank_bot","shank_center"]),
 632                   str("Screw has no unthreaded shank so anchor \"",anchor,"\" is not allowed"));
 633   anchor_list = [
 634          named_anchor("top", [0,0,offset+head_height+flat_cbore_height]),
 635          named_anchor("bot", [0,0,-length-shoulder_full+offset]),
 636          named_anchor("center", [0,0, -length/2 - shoulder_full/2 + head_height/2 + offset]),
 637          named_anchor("head_top", [0,0,head_height+offset]),
 638          named_anchor("head_bot", [0,0,-flat_height+offset]),
 639          named_anchor("head_center", [0,0,(head_height-flat_height)/2+offset]),
 640          if (_shoulder_len>0) named_anchor("shoulder_top", [0,0,offset-flat_height]),
 641          if (_shoulder_len>0) named_anchor("shoulder_bot", [0,0,offset-shoulder_full]),
 642          if (_shoulder_len>0) named_anchor("shoulder_center", [0,0,offset-flat_height-_shoulder_len/2]),
 643          named_anchor("shaft_top", [0,0,-_shoulder_len-flat_height+offset]),
 644          named_anchor("shaft_bot", [0,0,-length-shoulder_full+offset]),
 645          named_anchor("shaft_center", [0,0,(-_shoulder_len-flat_height-length-shoulder_full)/2+offset]),
 646          if (shank_len>0) named_anchor("shank_top", [0,0,-_shoulder_len-flat_height+offset]),
 647          if (shank_len>0) named_anchor("shank_bot", [0,0,-shank_len-_shoulder_len-flat_height+offset]),
 648          if (shank_len>0) named_anchor("shank_center", [0,0,-shank_len/2-_shoulder_len-flat_height+offset]),
 649          named_anchor("threads_top", [0,0,-shank_len-_shoulder_len-flat_height+offset]),
 650          named_anchor("threads_bot", [0,0,-length-shoulder_full+offset]),
 651          named_anchor("threads_center", [0,0,(-shank_len-length-_shoulder_len-shoulder_full-flat_height)/2+offset])
 652   ];
 653   rad_scale = _internal? (1/cos(180/sides)) : 1;
 654   islop = _internal ? 4*get_slop() : 0;
 655   vnf = head=="hex" && atype=="head" && counterbore==0 ? linear_sweep(hexagon(id=head_diam*rad_scale),height=head_height,center=true) : undef;
 656   head_diam_full = head=="hex" ? 2*head_diam/sqrt(3) : head_diam;
 657   attach_d = in_list(atype,["threads","shank","shaft"]) ? d_major 
 658            : atype=="screw" ? max(d_major,_shoulder_diam,default(head_diam_full,0))
 659            : atype=="shoulder" ? _shoulder_diam
 660            : is_def(vnf) ? undef
 661            : head_diam_full;
 662   attach_l = atype=="shaft" ? length-(_shoulder_len>0?0:flat_height)
 663            : atype=="shoulder" ? _shoulder_len
 664            : atype=="shank" ? shank_len
 665            : atype=="threads" ? thread_len
 666            : atype=="screw" ? length+head_height+shoulder_full + flat_cbore_height
 667            : is_def(vnf) ? undef
 668            : head_height+flat_height+flat_cbore_height;
 669   bevelsize = default(bevelsize, d_major/12);
 670   bevel1 = first_defined([bevel1,bevel,true]);
 671   bevel2 = first_defined([bevel2,bevel,headless && _shoulder_len==0 && shank_len==0]);
 672   attachable(
 673              vnf = vnf, 
 674              d = u_add(u_mul(attach_d, rad_scale), islop),
 675              l = attach_l,
 676              orient = orient,
 677              anchor = anchor,
 678              spin = spin,
 679              anchors=anchor_list)
 680   {
 681     up(offset)
 682       difference(){
 683         union(){
 684           screw_head(spec,details,counterbore=counterbore,flat_height=flat_height,
 685                      slop=islop,teardrop=_teardrop);
 686           if (_shoulder_len>0)
 687             up(eps_shoulder-flat_height){
 688               if (_teardrop!=false) //////
 689                 teardrop(d=_shoulder_diam*rad_scale+islop,cap_h=is_num(_teardrop) ? (_shoulder_diam*rad_scale+islop)/2*(1+_teardrop):undef,
 690                          h=_shoulder_len+eps_shoulder, anchor=FRONT, orient=BACK, $fn=sides);
 691               else
 692                 cyl(d=_shoulder_diam*rad_scale+islop, h=_shoulder_len+eps_shoulder, anchor=TOP, $fn=sides, chamfer1=details ? _shoulder_diam/30:0);
 693             }
 694           if (shank_len>0 || pitch==0){
 695             L = pitch==0 ? length - (_shoulder_len==0?flat_height:0) : shank_len;
 696             bevsize = (_internal ? -1 : 1)*bevelsize;
 697             bev1 = pitch!=0 ? 0
 698                  : bevel1==true ? bevsize
 699                  : bevel1==false ? 0
 700                  : bevel1=="reverse" ? -bevsize
 701                  : bevel1;
 702             bev2 = pitch!=0 ? 0
 703                  : bevel2==true ? bevsize
 704                  : bevel2==false ? 0
 705                  : bevel2=="reverse" ? -bevsize
 706                  : bevel2;
 707             down(_shoulder_len+flat_height-eps_shank)
 708               if (_teardrop!=false)  ///////
 709                 teardrop(d=d_major*rad_scale+islop, cap_h=is_num(_teardrop) ? (d_major*rad_scale+islop)/2*(1+_teardrop) : undef,
 710                          h=L+eps_shank, anchor=FRONT, orient=BACK, $fn=sides, chamfer1=bev1, chamfer2=bev2);
 711               else
 712                 cyl(d=d_major*rad_scale+islop, h=L+eps_shank, anchor=TOP, $fn=sides, chamfer1=bev1, chamfer2=bev2);
 713           }
 714           if (thread_len>0 && pitch>0){
 715             down(_shoulder_len+flat_height+shank_len-eps_thread)
 716                   threaded_rod([mean(struct_val(threadspec, "d_minor")),
 717                                 mean(struct_val(threadspec, "d_pitch")),
 718                                 d_major], 
 719                      pitch = struct_val(threadspec, "pitch"),
 720                      l=thread_len+eps_thread, left_handed=false, internal=_internal, 
 721                      bevel1=bevel1,
 722                      bevel2=bevel2,teardrop=_teardrop,
 723                      blunt_start=blunt_start, blunt_start1=blunt_start1, blunt_start2=blunt_start2, 
 724                      $fn=sides, anchor=TOP);
 725            }
 726             
 727         }
 728         if (!_internal) _driver(spec);
 729       }
 730     children();
 731   }  
 732}
 733
 734
 735
 736// Module: screw_hole()
 737// Synopsis: Creates a screw hole.
 738// SynTags: Geom
 739// Topics: Threading, Screws
 740// See Also: screw()
 741// Usage:
 742//   screw_hole([spec], [head], [thread=], [length=|l=], [oversize=], [hole_oversize=], [teardrop=], [head_oversize], [tolerance=], [$slop=], [blunt_start=], [anchor=], [atype=], [orient=], [spin=]) [ATTACHMENTS];
 743// Description:
 744//   Create a screw hole mask.  See [screw and nut parameters](#section-screw-and-nut-parameters) for details on the parameters that define a screw.
 745//   The screw hole can be threaded to receive a screw or it can be an unthreaded clearance hole.  
 746//   The tolerance determines the dimensions of the screw
 747//   based on ISO and ASME standards.  Screws fabricated at those dimensions will mate properly with standard hardware.
 748//   The $slop argument makes the hole larger by 4*$slop to account for printing overextrusion.  It defaults to 0.
 749//   .
 750//   You can generate a screw specification from {{screw_info()}}, possibly create a modified version, and pass that in rather than giving the parameters.
 751//   .
 752//   The tolerance should be a nut tolerance for a threaded hole or a clearance hole tolerance for clearance holes.
 753//   For clearance holes, the UTS tolerances are "normal", "loose" and "close".  ASME also specifies the same naming for metric clearance holes.
 754//   However, ISO gives "fine", "medium" and "coarse" instead.  This function accepts all of these in either system.  It also takes "tight" to be equivalent to "close",
 755//   even though no standard suggests it, because it's a natural opposite of "loose".  The official tolerance designations for ISO are "H12" for "fine", "H13" for "medium"
 756//   and "H14" for "coarse".  These designations will also work, but only for metric holes.  You can also set tolerance to 0 or "none" to produce holes at the nominal size.
 757//   .
 758//   If you want to produce holes for tapping you can use a tolerance of "tap".  This produces a hole of the nominal screw diameter reduced by the thread pitch.  You may still
 759//   need to adjust $slop for best results.  Some people screw machine screws directly into plastic without tapping.  This works better with a somewhat larger hole, so
 760//   a tolerance of "self tap" produces such a hole.  Note that this tolerance also makes the default bevel2=true to bevel the top, which makes it much easier
 761//   to start the screw.  The "self tap" tolerance subtracts `0.72 * pitch` when pitch is below 1mm, `0.6 * pitch` when the pitch is over 1.5mm, and it interpolates between.
 762//   It was tested in PLA with a Prusa MK3S and $slop=0.05 and worked on UTS screws from #2 up to 1/2 inch.  
 763//   .
 764//   The counterbore parameter adds a cylindrical clearance hole above the screw shaft.  For flat heads it extends above the flathead and for other screw types it 
 765//   replaces the head with a cylinder large enough in diameter for the head to fit.  For a flat head you must specify the length of the counterbore.  For other heads you can
 766//   set counterbore to true and it will be sized to match the head height.  The counterbore will extend 0.01 above the TOP of the hole mask to ensure no
 767//   problems with differences.  Note that the counterbore defaults to true for non-flathead screws.  If you want the actual head shape to appear, set counterbore to zero.
 768//   .
 769//   For 3d printing circular holes can be problematic.  One solution is to use octagonal holes, setting $fn=8.  Another option is to use a teardrop hole, which
 770//   can be accomplished by setting `teardrop=true`.  The point of the teardrop will point in the Y direction (BACK) so you will need to ensure that you orient it
 771//   correctly in your final model.  
 772//   .
 773//   Anchoring for screw_hole() is the same as anchoring for {{screw()}}, with all the same anchor types and named anchors.  If you specify a counterbore it is treated as
 774//   the "head", or in the case of flat heads, it becomes part of the head.  If you make a teardrop hole the point is ignored for purposes of anchoring.
 775// Arguments:
 776//   spec = screw specification, e.g. "M5x1" or "#8-32".  See [screw naming](#subsection-screw-naming).  This can also be a screw specification structure of the form produced by {{screw_info()}}.  
 777//   head = head type.  See [screw heads](#subsection-screw-heads)  Default: none
 778//   ---
 779//   thread = thread type or specification for threaded masks, true to make a threaded mask with the standard threads, or false to make an unthreaded mask.  See [screw pitch](#subsection-standard-screw-pitch). Default: false
 780//   teardrop = If true, adds a teardrop profile to the hole for 3d printability of horizontal holes. If numeric, specifies the proportional extra distance of the teardrop flat top from the screw center, or set to "max" for a pointed teardrop. Default: false
 781//   oversize = amount to increase diameter of the screw hole (hole and countersink).  A scalar or length 2 vector.  Default: use computed tolerance
 782//   hole_oversize = amount to increase diameter of the hole.  Overrides the use of tolerance and replaces any settings given in the screw specification. 
 783//   head_oversize = amount to increase diameter of head.  Overrides the user of tolerance and replaces any settings given in the screw specification.  
 784//   length / l= length of screw (in mm)
 785//   counterbore = set to length of counterbore, or true to make a counterbore equal to head height.  Default: false for flat heads and headless, true otherwise
 786//   tolerance = threading or clearance hole tolerance.  For internal threads, detrmines actual thread geometry based on nominal sizing.  See [tolerance](#subsection-tolerance). Default is "2B" for UTS and 6H for ISO.  For clearance holes, determines how much clearance to add.  Default is "normal".  
 787//   bevel = if true create bevel at both ends of hole.  Default: see below
 788//   bevel1 = if true create bevel at bottom end of hole.  Default: false
 789//   bevel2 = if true create bevel at top end of hole.     Default: true when tolerance="self tap", false otherwise
 790//   blunt_start = if true and hole is threaded, create blunt start threads.  Default: true
 791//   blunt_start1 = if true and hole is threaded, create blunt start threads at bottom end.
 792//   blunt_start2 = if true and hole is threaded, create blunt start threads top end.
 793//   $slop = add extra gap to account for printer overextrusion.  Default: 0
 794//   atype = anchor type, one of "screw", "head", "shaft", "threads", "shank"
 795//   anchor = Translate so anchor point on the shaft is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `CENTER`
 796//   spin = Rotate this many degrees around the Z axis after anchor.  See [spin](attachments.scad#subsection-spin).  Default: `0`
 797//   orient = Vector to rotate top towards, after spin.  See [orient](attachments.scad#subsection-orient).  Default: `UP`
 798// Side Effects:
 799//   `$screw_spec` is set to the spec specification structure. 
 800// Anchor Types:
 801//   screw = the entire screw (default)
 802//   head = screw head (invalid for headless screws)
 803//   shaft = screw shaft
 804//   shank = unthreaded section of shaft (invalid if screw is fully threaded)
 805//   threads = threaded section of screw     
 806// Named Anchors:
 807//   "top" = top of screw
 808//   "bot" = bottom of screw
 809//   "center" = center of screw
 810//   "head_top" = top of head (invalid for headless screws)
 811//   "head_bot" = bottom of head (invalid for headless screws)
 812//   "head_center" = center of head (invalid for headless screws)
 813//   "shaft_top" = top of shaft
 814//   "shaft_bot" = bottom of shaft
 815//   "shaft_center" = center of shaft
 816//   "shank_top" = top of shank (invalid if screw is fully threaded)
 817//   "shank_bot" = bottom of shank (invalid if screw is fully threaded)
 818//   "shank_center" = center of shank (invalid if screw is fully threaded)
 819//   "threads_top" = top of threaded portion of screw (invalid if thread_len=0)
 820//   "threads_bot" = bottom of threaded portion of screw (invalid if thread_len=0)
 821//   "threads_center" = center of threaded portion of screw (invalid if thread_len=0)
 822// Example: Counterbored clearance hole
 823//   diff()
 824//     cuboid(20)
 825//       attach(TOP)
 826//         screw_hole("1/4-20,.5",head="socket",counterbore=5,anchor=TOP);
 827// Example: Clearance hole for flathead 
 828//   diff()
 829//     cuboid(20)
 830//       attach(TOP)
 831//          screw_hole("1/4-20,.5",head="flat",counterbore=0,anchor=TOP);
 832// Example: Threaded hole, with inward bevel at the base
 833//   bottom_half()
 834//     diff()
 835//       cuboid(20)
 836//         attach(FRONT)
 837//           screw_hole("M16,15",anchor=TOP,thread=true,bevel1="reverse");
 838function screw_hole(spec, head, thread, oversize, hole_oversize, head_oversize, 
 839             length, l, thread_len, tolerance=undef, counterbore, teardrop=false,
 840             bevel, bevel1, bevel2, blunt_start, blunt_start1, blunt_start2, 
 841             atype="screw",anchor=CENTER,spin=0, orient=UP)
 842    = no_function("screw_hole");
 843module screw_hole(spec, head, thread, oversize, hole_oversize, head_oversize, 
 844             length, l, thread_len, tolerance=undef, counterbore, teardrop=false,
 845             bevel, bevel1, bevel2, blunt_start, blunt_start1, blunt_start2, 
 846             atype="screw",anchor=CENTER,spin=0, orient=UP)
 847{
 848   screwspec = _get_spec(spec, "screw_info", "screw_hole", 
 849                        thread=thread, head=head);
 850   bevel1 = first_defined([bevel1,bevel,false]);
 851   bevel2 = first_defined([bevel2,bevel,tolerance=="self tap"]);
 852   thread = default(thread,false);
 853   checkhead = struct_val(screwspec,"head");
 854   default_counterbore = checkhead=="none" || starts_with(checkhead,"flat") ? 0 : true;
 855   counterbore = default(counterbore, default_counterbore);
 856   dummy = _validate_screw_spec(screwspec);
 857   threaded = thread==true || (is_finite(thread) && thread>0) || (is_undef(thread) && struct_val(screwspec,"pitch")>0);
 858   oversize = force_list(oversize,2);
 859   hole_oversize = first_defined([hole_oversize, oversize[0],struct_val(screwspec,"shaft_oversize")]);
 860   head_oversize = first_defined([head_oversize, oversize[1],struct_val(screwspec,"head_oversize")]);
 861   if (threaded || is_def(hole_oversize) || tolerance==0 || tolerance=="none") {
 862     default_tag("remove")
 863       screw(spec,head=head,thread=thread,shaft_undersize=u_mul(-1,hole_oversize), head_undersize=u_mul(-1,head_oversize),
 864             blunt_start=blunt_start, blunt_start1=blunt_start1, blunt_start2=blunt_start2, 
 865             length=length,l=l,thread_len=thread_len, tolerance=tolerance, _counterbore=counterbore,
 866             bevel1=bevel1, bevel2=bevel2, 
 867             atype=atype, anchor=anchor, spin=spin, orient=orient, _internal=true, _teardrop=teardrop)
 868         children();
 869   }
 870   else {
 871     tolerance = default(tolerance, "normal");
 872     pitch = struct_val(screwspec,"pitch");
 873     dummy3 = assert((downcase(tolerance) != "tap" && downcase(tolerance)!="self tap") || pitch!=0,
 874                     "\"tap\" clearance requires a pitch size, but pitch is set to zero");
 875     // UTS clearances from ASME B18.2.8
 876     UTS_clearance = [
 877       [ // Close fit
 878         [0.1120 * INCH,0.008*INCH],
 879         [0.1250 * INCH, 1/64*INCH],
 880         [7/16   * INCH, 1/64*INCH],
 881         [1/2    * INCH, 1/32*INCH],
 882         [1.25   * INCH, 1/32*INCH],
 883         [1.375  * INCH, 1/16*INCH]
 884       ],
 885       [ // Normal fit
 886         [0.1120 * INCH, 1/64*INCH],
 887         [0.1250 * INCH, 1/32*INCH],
 888         [7/16   * INCH, 1/32*INCH],
 889         [1/2    * INCH, 1/16*INCH],
 890         [7/8    * INCH, 1/16*INCH],
 891         [1      * INCH, 3/32*INCH],
 892         [1.25   * INCH, 3/32*INCH],
 893         [1.375  * INCH,  1/8*INCH],
 894       ],
 895       [ // Loose fit
 896         [0.1120 * INCH, 1/32*INCH],
 897         [0.1250 * INCH, 3/64*INCH],
 898         [7/16   * INCH, 3/64*INCH],
 899         [1/2    * INCH, 7/64*INCH],
 900         [5/8    * INCH, 7/64*INCH],
 901         [3/4    * INCH, 5/32*INCH],
 902         [1      * INCH, 5/32*INCH],
 903         [1.125  * INCH, 3/16*INCH],
 904         [1.25   * INCH, 3/16*INCH],
 905         [1.375  * INCH,15/64*INCH]
 906       ]
 907     ];
 908     // ISO clearances appear in ASME B18.2.8 and ISO 273
 909     ISO_clearance = [
 910       [ // Close, Fine, H12 
 911         [2.5, 0.1],
 912         [3.5, 0.2],
 913         [4,   0.3],
 914         [5,   0.3],
 915         [6,   0.4],
 916         [8,   0.4],
 917         [10,  0.5],
 918         [12,  1],
 919         [42,  1],
 920         [48,  2],
 921         [80,  2],
 922         [90,  3],
 923         [100, 4],
 924       ],
 925       [  // Normal, Medium, H13
 926         [1.6, 0.2],
 927         [2,   0.4],
 928         [3.5, 0.4],
 929         [4,   0.5],
 930         [5,   0.5],
 931         [6,   0.6],
 932         [8,   1],
 933         [10,  1],
 934         [12,  1.5],
 935         [16,  1.5],
 936         [20,  2],
 937         [24,  2],
 938         [30,  3],
 939         [42,  3],
 940         [48,  4],
 941         [56,  6],
 942         [90,  6],
 943         [100, 7],
 944       ],
 945       [  // Loose, Coarse, H14
 946         [1.6, 0.25],
 947         [2,   0.3],
 948         [3,   0.6],
 949         [3.5, 0.7],
 950         [4,   0.8],
 951         [5,   0.8],
 952         [6,   1],
 953         [8,   2],
 954         [10,  2],
 955         [12,  2.5],
 956         [16,  2.5],
 957         [20,  4],
 958         [24,  4],
 959         [30,  5],
 960         [36,  6],
 961         [42,  6],
 962         [48,  8],
 963         [56, 10],
 964         [72, 10],
 965         [80, 11],
 966         [90, 11],
 967         [100,12],
 968       ]
 969     ];
 970     tol_ind = in_list(downcase(tolerance), ["close", "fine", "tight"]) ? 0
 971             : in_list(downcase(tolerance), ["normal", "medium", "tap", "self tap"]) ? 1
 972             : in_list(downcase(tolerance), ["loose", "coarse"]) ? 2
 973             : in_list(tolerance, ["H12","H13","H14"]) ?
 974                   assert(struct_val(screwspec,"system")=="ISO", str("Hole tolerance ", tolerance, " only allowed with ISO screws"))
 975                   parse_int(substr(tolerance,1))
 976             : assert(false,str("Unknown tolerance ",tolerance, " for clearance hole"));
 977     tol_table = struct_val(screwspec,"system")=="UTS" ? UTS_clearance[tol_ind] : ISO_clearance[tol_ind];
 978     tol_gap = lookup(_nominal_diam(screwspec), tol_table);
 979     // If we got here, hole_oversize is undefined and oversize is undefined
 980     hole_oversize = downcase(tolerance)=="tap" ? -pitch
 981                   : downcase(tolerance)=="self tap" ? -pitch*lookup(pitch,[[1,0.72],[1.5,.6]])
 982                   : tol_gap;
 983     head_oversize = default(head_oversize, tol_gap);
 984     default_tag("remove")     
 985       screw(spec,head=head,thread=0,shaft_undersize=-hole_oversize, head_undersize=-head_oversize, 
 986             length=length,l=l,thread_len=thread_len, _counterbore=counterbore,
 987             bevel1=bevel1, bevel2=bevel2, bevelsize=pitch>0?pitch:undef,
 988             atype=atype, anchor=anchor, spin=spin, orient=orient, _internal=true, _teardrop=teardrop)
 989         children();
 990   }
 991} 
 992
 993// Module: shoulder_screw()
 994// Synopsis: Creates a shoulder screw.
 995// SynTags: Geom
 996// Topics: Threading, Screws
 997// See Also: screw(), screw_hole()
 998// Usage:
 999//   shoulder_screw(s, d, length, [head=], [thread_len=], [tolerance=], [head_size=], [drive=], [drive_size=], [thread=], [undersize=], [shaft_undersize=], [head_undersize=], [shoulder_undersize=],[atype=],[anchor=],[orient=],[spin=]) [ATTACHMENTS];
1000// Description:
1001//   Create a shoulder screw.  See [screw and nut parameters](#section-screw-and-nut-parameters) for details on the parameters that define a screw.
1002//   The tolerance determines the dimensions of the screw
1003//   based on ISO and ASME standards.  Screws fabricated at those dimensions will mate properly with standard hardware.
1004//   Note that the $slop argument does not affect the size of screws: it only adjusts screw holes.  This will work fine
1005//   if you are printing both parts, but if you need to mate printed screws to metal parts you may need to adjust the size
1006//   of the screws, which you can do with the undersize arguments.
1007//   .
1008//   Unlike a regular screw, a shoulder screw is based on its shoulder dimensions: diameter and length.  The ISO and ASME standards
1009//   specify for a given shoulder diameter the thread size and even the length of the threads.  Note that these standards specify only
1010//   a small range of sizes.  You can specify a shoulder screw by giving the system, either "ISO" or "UTS" and the shoulder diameter
1011//   and length, and shoulder_screw() will supply the other parameters.
1012//   .
1013//   Hardware sources like McMaster sell many screws that don't comply with the standards.  If you want to make such a screw then
1014//   you can specify parameters like thread_len, the length of the threaded portion below the shoulder, and you can choose a different head
1015//   type.  You will need to specify the size of the head, since it cannot be looked up in tables.  You can also 
1016//   generate a screw specification from {{screw_info()}}, possibly create a modified version using {{struct_set()}}, and pass that in rather than giving the parameters.
1017//   .
1018//   The anchors and anchor types are the same as for {{screw()}} except that there is an anchor type for the shoulder and an additional set of named anchors
1019//   refering to parts of the shoulder.  
1020// Arguments:
1021//   s = screw system to use, case insensitive, either "ISO", "UTS", "english" or "metric", or a screw name or specification.  See [screw naming](#subsection-screw-naming).
1022//   d = nominal shoulder diameter in mm for ISO or inches for UTS
1023//   length = length of the shoulder (in mm)
1024//   ---
1025//   thread_len = length of threads
1026//   tolerance = screw tolerance.  Determines actual screw thread geometry based on nominal sizing.  See [tolerance](#subsection-tolerance). Default is "2A" for UTS and "6g" for ISO.
1027//   drive = drive type.  See [screw heads](#subsection-screw-heads) set to "none" for no drive.  Default: "hex"
1028//   drive_size = size of the drive recess
1029//   thread = thread type or specification. See [screw pitch](#subsection-standard-screw-pitch). Default: "coarse"
1030//   spec = screw specification to define the thread size 
1031//   head_size = scalar or vector to give width or [width, height].  If you only give width, height is computed using a formula for socket heads.  For flat head screws the second value in the vector is the sharp size; if you don't give it then the sharp size will be 12% more than the given size
1032// Side Effects:
1033//   `$screw_spec` is set to the spec specification structure. 
1034// Anchor Types:
1035//   screw = the entire screw (default)
1036//   head = screw head (invalid for headless screws)
1037//   shoulder = the shoulder
1038//   shaft = screw shaft
1039//   threads = threaded section of screw     
1040// Named Anchors:
1041//   "top" = top of screw
1042//   "bot" = bottom of screw
1043//   "center" = center of screw
1044//   "head_top" = top of head (invalid for headless screws)
1045//   "head_bot" = bottom of head (invalid for headless screws)
1046//   "head_center" = center of head (invalid for headless screws)
1047//   "shoulder_top" = top of shoulder
1048//   "shoulder_bot" = bottom of shoulder
1049//   "shoulder_center" = center of shoulder
1050//   "shaft_top" = top of shaft
1051//   "shaft_bot" = bottom of shaft
1052//   "shaft_center" = center of shaft
1053//   "threads_top" = top of threaded portion of screw (invalid if thread_len=0)
1054//   "threads_bot" = bottom of threaded portion of screw (invalid if thread_len=0)
1055//   "threads_center" = center of threaded portion of screw (invalid if thread_len=0)
1056// Example: ISO shoulder screw
1057//   shoulder_screw("iso",10,length=20);
1058// Example: English shoulder screw
1059//   shoulder_screw("english",1/2,length=20);
1060// Example: Custom example.  You must specify thread_len and head_size when creating custom configurations.  
1061//   shoulder_screw("M6", 9.3, length=17, thread_len=8, head_size=14);
1062// Example: Another custom example:
1063//   shoulder_screw("M6", 9.3, length=17, thread_len=8, head_size=14, head="button", drive="torx");
1064// Example: Threadless 
1065//   shoulder_screw("iso",10,length=15,thread=0);
1066// Example: No drive recess
1067//   shoulder_screw("iso",10,length=15,drive="none");
1068// Example: Headless
1069//   shoulder_screw("iso", 16, length=20, head="none");
1070// Example: Changing head height
1071//   shoulder_screw("iso", 16, length=20, head_size=[24,5]);
1072function shoulder_screw(s,d,length,head, thread_len, tolerance, head_size, drive, drive_size, thread,
1073                      undersize, shaft_undersize, head_undersize, shoulder_undersize=0,
1074                      blunt_start, blunt_start1, blunt_start2, 
1075                      atype="screw", anchor=BOT, orient,spin) = no_function("shoulder_screw");
1076module shoulder_screw(s,d,length,head, thread_len, tolerance, head_size, drive, drive_size, thread,
1077                      undersize, shaft_undersize, head_undersize, shoulder_undersize=0,
1078                      blunt_start, blunt_start1, blunt_start2, 
1079                      atype="screw", anchor=BOT, orient,spin)
1080{
1081  d1= assert(is_num(d) && d>0, "Must specify shoulder diameter")
1082      assert (is_num(length) && length>0, "Must specify shoulder length");
1083  systemOK=is_string(s) && in_list(downcase(s),["iso","metric","uts","english"]);
1084  info_temp = systemOK ? undef
1085            : is_struct(s) ? s
1086            : screw_info(s);
1087  infoOK = systemOK ? false
1088         : _nominal_diam(info_temp) && struct_val(info_temp,"pitch") && struct_val(info_temp,"system");
1089  d2=assert(systemOK || infoOK, "System must be \"ISO\", \"UTS\", \"English\" or \"metric\" or a valid screw specification string")
1090     assert(!is_struct(s) || num_defined([drive, drive_size, thread, head])==0,
1091            "With screw struct, \"head\", \"drive\", \"drive_size\" and \"thread\" are not allowed");
1092  drive = drive=="none" ? undef : default(drive,"hex");
1093  thread = default(thread,"coarse");
1094  head = default(head, "socket");                                    
1095  usersize = systemOK ? undef : s;
1096  system = systemOK ? s : struct_val(info_temp,"system");
1097  undersize = is_undef(undersize) ? undersize
1098            : is_num(undersize) ? [undersize,undersize]
1099            : undersize;
1100  shaft_undersize = first_defined([shaft_undersize, undersize[0], 0]);
1101  head_undersize = first_defined([head_undersize, undersize[1], 0]);
1102  
1103  iso = in_list(downcase(system), ["iso","metric"]);
1104
1105  factor = iso ? 1 : INCH;
1106
1107  table = iso ?   //  iso shoulder screws, hex drive socket head  ISO 7379
1108                  //  Mcmaster has variations like 12mm shoulder for m10, 6mm shoulder for M5
1109                  // shld   screw  thread  head  hex  hex     head  
1110                  // diam   size   length  diam      depth     ht 
1111                  [                                                 
1112                     [6.5,  ["M5",   9.5,   10,   3,  2.4,     4.5]],
1113                     [8  ,  ["M6",   11 ,   13,   4,  3.3,     5.5]],
1114                     [10 ,  ["M8",   13 ,   16,   5,  4.2,     7  ]],
1115                     [13 ,  ["M10",  16 ,   18,   6,  4.9,     9  ]],
1116                     [16 ,  ["M12",  18 ,   24,   8,  6.6,    11  ]],
1117                     [20 ,  ["M16",  22 ,   30,  10,  8.8,    14  ]],
1118                     [25 ,  ["M20",  27 ,   36,  12,  10 ,    16  ]]
1119                   ]
1120        :
1121                   // UTS shoulder screws, b18.3 (table 13)
1122                   // sh diam  screw   thread len, head diam   hex size  hex depth
1123                   [
1124                      [1/8  ,  ["#4",     5/32 ,    1/4      ,  5/64   ,  0.067]],
1125                      [5/32 ,  ["#6",     3/16 ,    9/32     ,  3/32   ,  0.067]],
1126                      [3/16 ,  ["#8",     3/16 ,    5/16     ,  3/32   ,  0.079]],
1127                      [1/4  ,  ["#10",    3/8  ,    3/8      ,  1/8    ,  0.094]],
1128                      [5/16 ,  ["1/4",    7/16 ,    7/16     ,  5/32   ,  0.117]],
1129                      [3/8  ,  ["5/16",   1/2  ,    9/16     ,  3/16   ,  0.141]],
1130                      [1/2  ,  ["3/8",    5/8  ,    3/4      ,  1/4    ,  0.188]],
1131                      [5/8  ,  ["1/2",    3/4  ,    7/8      ,  5/16   ,  0.234]],
1132                      [3/4  ,  ["5/8",    7/8  ,    1        ,  3/8    ,  0.281]],
1133                      [1    ,  ["3/4",    1    ,    1+5/16   ,  1/2    ,  0.375]],
1134                      [1+1/4,  ["7/8",    1+1/8,    1+3/4    ,  5/8    ,  0.469]],
1135                      [1+1/2,  ["1.125",  1+1/2,    2+1/8    ,  7/8    ,  0.656]],
1136                      [1+3/4,  ["1.25",   1+3/4,    2+3/8    ,  1      ,  0.750]],
1137                      [2    ,  ["1.5",    2    ,    2+3/4    ,  1+1/4  ,  0.937]]
1138                   ];           
1139  entry = struct_val(table, d);
1140  shoulder_diam = d * factor - shoulder_undersize;
1141  spec = first_defined([usersize, entry[0]]);
1142  dummy2=assert(is_def(spec),"No shoulder screw found with specified diameter");
1143  thread_len = first_defined([thread_len, u_mul(entry[1],factor)]);
1144  head_size = first_defined([head_size, u_mul(entry[2],factor)]);
1145  drive_size = first_defined([drive_size, u_mul(entry[3],factor)]);
1146  drive_depth = u_mul(entry[4],factor);
1147  head_height_table = iso? first_defined([entry[5],d/2+1.5])
1148                    : d<3/4 ? (d/2 + 1/16)*INCH
1149                    : (d/2 + 1/8)*INCH;
1150  shoulder_tol = tolerance==0 || tolerance=="none" ? 0
1151               : iso ? lookup(d, [[10,0.03],[13,0.037],[16,0.037],[20,0.046]])
1152               : 1; //0.003 * INCH;
1153  info = is_struct(s) ? s
1154       : screw_info(spec, head, drive, drive_size=drive_size, thread=thread);
1155
1156  final_headsize = is_num(head_size) ? head_size
1157                 : head_size[0];
1158  d5=assert(is_num(final_headsize), "Head size invalid or missing");
1159  final_sharpsize =  head!="flat" ? undef : is_vector(head_size)? head_size[1] : final_headsize*1.12;
1160  head_height_flat = head!="flat" ? undef : (final_sharpsize-(shoulder_diam-shoulder_tol))/2/tan(struct_val(info,"head_angle")/2);
1161  headfields = concat(
1162                      ["head_size", final_headsize],
1163                      head=="flat" ? ["head_size_sharp", final_sharpsize, "head_height", head_height_flat]
1164                                   : ["head_height",   is_vector(head_size) ? head_size[1]
1165                                                     : is_num(head_height_table)? head_height_table
1166                                                     : final_headsize/2 + 1.5],
1167                      is_def(drive_depth) ? ["drive_depth", drive_depth] :[]
1168                     );
1169  dummy3=assert(is_num(length) && length>0, "Must give a positive shoulder length");
1170  screw(struct_set(info, headfields),
1171        _shoulder_len = length, _shoulder_diam = shoulder_diam-shoulder_tol,
1172        length=thread_len, tolerance=tolerance, shaft_undersize=shaft_undersize, head_undersize=head_undersize,
1173        blunt_start=blunt_start, blunt_start1=blunt_start1, blunt_start2=blunt_start2,                 
1174        atype=atype, anchor=anchor, orient=orient, spin=spin)
1175    children();
1176}        
1177                     
1178
1179
1180module _driver(spec)
1181{
1182  drive = struct_val(spec,"drive");
1183  if (is_def(drive) && drive!="none") {
1184    head = struct_val(spec,"head");
1185    diameter = _nominal_diam(spec);
1186    drive_size = struct_val(spec,"drive_size");
1187    drive_diameter = struct_val(spec, "drive_diameter");
1188    drive_depth = first_defined([struct_val(spec, "drive_depth"), .7*diameter]); // Note hack for unspecified depth
1189    head_top = starts_with(head,"flat") || head=="none" ? 0 :
1190               struct_val(spec,"head_height");
1191    up(head_top-drive_depth){
1192      // recess should be positioned with its bottom center at (0,0) and the correct recess depth given above
1193      if (drive=="phillips") phillips_mask(drive_size,anchor=BOTTOM);
1194      if (drive=="torx") torx_mask(size=drive_size, l=drive_depth+1, center=false);
1195      if (drive=="hex") hex_drive_mask(drive_size,drive_depth+1,anchor=BOT);
1196      if (drive=="slot") {
1197          head_width = first_defined([u_add(struct_val(spec, "head_size"),struct_val(spec,"head_oversize",0)), diameter]);
1198          cuboid([2*head_width, drive_size, drive_depth+1],anchor=BOTTOM);
1199      }
1200    }
1201  }
1202}
1203
1204
1205function _ISO_thread_tolerance(diameter, pitch, internal=false, tolerance=undef) =
1206  let(
1207    P = pitch,
1208    H = P*sqrt(3)/2,
1209    tolerance = first_defined([tolerance, internal?"6H":"6g"]),
1210
1211    pdiam = diameter - 2*3/8*H,          // nominal pitch diameter
1212    mindiam = diameter - 2*5/8*H,        // nominal minimum diameter
1213
1214    EI = [   // Fundamental deviations for nut thread
1215          ["G", 15+11*P],
1216          ["H", 0],            // Standard practice
1217         ],
1218
1219    es = [    // Fundamental deviations for bolt thread
1220          ["e", -(50+11*P)],   // Exceptions if P<=0.45mm
1221          ["f", -(30+11*P)],
1222          ["g", -(15+11*P)],   // Standard practice
1223          ["h", 0]             // Standard practice for tight fit
1224         ],
1225
1226    T_d6 = 180*pow(P,2/3)-3.15/sqrt(P),
1227    T_d = [  // Crest diameter tolerance for major diameter of bolt thread
1228           [4, 0.63*T_d6],
1229           [6, T_d6],
1230           [8, 1.6*T_d6]
1231          ],
1232
1233    T_D1_6 = 0.2 <= P && P <= 0.8 ? 433*P - 190*pow(P,1.22) :
1234             P > .8 ? 230 * pow(P,0.7) : undef,
1235    T_D1 = [ // Crest diameter tolerance for minor diameter of nut thread
1236             [4, 0.63*T_D1_6],
1237             [5, 0.8*T_D1_6],
1238             [6, T_D1_6],
1239             [7, 1.25*T_D1_6],
1240             [8, 1.6*T_D1_6]
1241           ],
1242
1243    rangepts = [0.99, 1.4, 2.8, 5.6, 11.2, 22.4, 45, 90, 180, 300],
1244    d_ind = floor(lookup(diameter,hstack(rangepts,count(len(rangepts))))),
1245    avgd = sqrt(rangepts[d_ind]* rangepts[d_ind+1]),
1246
1247    T_d2_6 = 90*pow(P, 0.4)*pow(avgd,0.1),
1248    T_d2 = [ // Pitch diameter tolerance for bolt thread
1249             [3, 0.5*T_d2_6],
1250             [4, 0.63*T_d2_6],
1251             [5, 0.8*T_d2_6],
1252             [6, T_d2_6],
1253             [7, 1.25*T_d2_6],
1254             [8, 1.6*T_d2_6],
1255             [9, 2*T_d2_6],
1256           ],
1257
1258    T_D2 = [  // Tolerance for pitch diameter of nut thread
1259              [4, 0.85*T_d2_6],
1260              [5, 1.06*T_d2_6],
1261              [6, 1.32*T_d2_6],
1262              [7, 1.7*T_d2_6],
1263              [8, 2.12*T_d2_6]
1264           ],
1265
1266    internal = is_def(internal) ? internal : tolerance[1] != downcase(tolerance[1]),
1267    internalok = !internal || (
1268                               len(tolerance)==2 && str_find("GH",tolerance[1])!=undef && str_find("45678",tolerance[0])!=undef),
1269    tol_str = str(tolerance,tolerance),
1270    externalok = internal || (
1271                              (len(tolerance)==2 || len(tolerance)==4)
1272                                                          && str_find("efgh", tol_str[1])!=undef
1273                                                          && str_find("efgh", tol_str[3])!=undef
1274                                                          && str_find("3456789", tol_str[0]) != undef
1275                                                          && str_find("468", tol_str[2]) !=undef)
1276  )
1277  assert(internalok,str("Invalid internal thread tolerance, ",tolerance,".  Must have form <digit><letter>"))
1278  assert(externalok,str("invalid external thread tolerance, ",tolerance,".  Must have form <digit><letter> or <digit><letter><digit><letter>"))
1279  let(
1280    tol_num_pitch = parse_num(tol_str[0]),
1281    tol_num_crest = parse_num(tol_str[2]),
1282    tol_letter = tol_str[1]
1283  )
1284  assert(tol_letter==tol_str[3],str("Invalid tolerance, ",tolerance,".  Cannot mix different letters"))
1285  internal ?
1286    let(  // Nut case
1287      fdev = struct_val(EI,tol_letter)/1000,
1288      Tdval = struct_val(T_D1, tol_num_crest)/1000,
1289      Td2val = struct_val(T_D2, tol_num_pitch)/1000,
1290      bot=[diameter+fdev, diameter+fdev+Td2val+H/6],
1291      xdiam = [mindiam+fdev,mindiam+fdev+Tdval],
1292      pitchdiam = [pdiam + fdev, pdiam+fdev+Td2val]
1293    )
1294    [["pitch",P],["d_minor",xdiam], ["d_pitch",pitchdiam], ["d_major",bot],["basic",[mindiam,pdiam,diameter]]]
1295  :
1296    let( // Bolt case
1297      fdev = struct_val(es,tol_letter)/1000,
1298      Tdval = struct_val(T_d, tol_num_crest)/1000,
1299      Td2val = struct_val(T_d2, tol_num_pitch)/1000,
1300      mintrunc = P/8,
1301      d1 = diameter-5*H/4,
1302      maxtrunc = H/4 - mintrunc * (1-cos(60-acos(1-Td2val/4/mintrunc)))+Td2val/2,
1303      bot = [diameter-2*H+2*mintrunc+fdev, diameter-2*H+2*maxtrunc+fdev],
1304      xdiam = [diameter+fdev,diameter+fdev-Tdval],
1305      pitchdiam = [pdiam + fdev, pdiam+fdev-Td2val]
1306    )
1307    [["pitch",P],["d_major",xdiam], ["d_pitch",pitchdiam], ["d_minor",bot],["basic",[mindiam,pdiam,diameter]]];
1308
1309function _UTS_thread_tolerance(diam, pitch, internal=false, tolerance=undef) =
1310  let(
1311    d = diam/INCH,   // diameter in inches
1312    P = pitch/INCH,  // pitch in inches
1313    H = P*sqrt(3)/2,
1314    tolerance = first_defined([tolerance, internal?"2B":"2A"]),
1315    tolOK = in_list(tolerance, ["1A","1B","2A","2B","3A","3B"]),
1316    internal = tolerance[1]=="B"
1317  )
1318  assert(tolOK,str("Tolerance was ",tolerance,". Must be one of 1A, 2A, 3A, 1B, 2B, 3B"))
1319  let(
1320    LE = 9*P,   // length of engagement.  Is this right?
1321    pitchtol_2A = 0.0015*pow(d,1/3) + 0.0015*sqrt(LE) + 0.015*pow(P,2/3),
1322    pitchtol_table = [
1323                 ["1A", 1.500*pitchtol_2A],
1324                 ["2A",       pitchtol_2A],
1325                 ["3A", 0.750*pitchtol_2A],
1326                 ["1B", 1.950*pitchtol_2A],
1327                 ["2B", 1.300*pitchtol_2A],
1328                 ["3B", 0.975*pitchtol_2A]
1329               ],
1330     pitchtol = struct_val(pitchtol_table, tolerance),
1331     allowance = tolerance=="1A" || tolerance=="2A" ? 0.3 * pitchtol_2A : 0,
1332     majortol = tolerance == "1A" ? 0.090*pow(P,2/3) :
1333                tolerance == "2A" || tolerance == "3A" ? 0.060*pow(P,2/3) :
1334                pitchtol+pitch/4/sqrt(3),    // Internal case
1335     minortol = tolerance=="1B" || tolerance=="2B" ?
1336                    (
1337                      d < 0.25 ? constrain(0.05*pow(P,2/3)+0.03*P/d - 0.002, 0.25*P-0.4*P*P, 0.394*P)
1338                               : (P > 0.25 ? 0.15*P : 0.25*P-0.4*P*P)
1339                    ) :
1340                tolerance=="3B" ? constrain(0.05*pow(P,2/3)+0.03*P/d - 0.002, P<1/13 ? 0.12*P : 0.23*P-1.5*P*P, 0.394*P)
1341                     :0, // not used for external threads
1342     basic_minordiam = d - 5/4*H,
1343     basic_pitchdiam = d - 3/4*H,
1344     majordiam = internal ? [d,d] :          // A little confused here, paragraph 8.3.2
1345                          [d-allowance-majortol, d-allowance],
1346     pitchdiam = internal ? [basic_pitchdiam, basic_pitchdiam + pitchtol]
1347                          : [majordiam[1] - 3/4*H-pitchtol, majordiam[1]-3/4*H],
1348     minordiam = internal ? [basic_minordiam, basic_minordiam + minortol]
1349                          : [pitchdiam[0] - 3/4*H, basic_minordiam - allowance - H/8]   // the -H/8 is for the UNR case, 0 for UN case
1350    )
1351    [["pitch",P*INCH],["d_major",majordiam*INCH], ["d_pitch", pitchdiam*INCH], ["d_minor",minordiam*INCH],
1352     ["basic", INCH*[basic_minordiam, basic_pitchdiam, d]]];
1353
1354function _exact_thread_tolerance(d,P) =
1355   let(
1356       H = P*sqrt(3)/2,
1357       basic_minordiam = d - 5/4*H,
1358       basic_pitchdiam = d - 3/4*H
1359      )
1360    [["pitch", P], ["d_major", [d,d]], ["d_pitch", [basic_pitchdiam,basic_pitchdiam]], ["d_minor", [basic_minordiam,basic_minordiam]],
1361     ["basic", [basic_minordiam, basic_pitchdiam, d]]];
1362
1363
1364// Takes a screw name as input and returns a list of the form
1365// [system, diameter, thread, length]
1366// where system is either "english" or "metric".  
1367
1368function _parse_screw_name(name) =
1369    let( commasplit = str_split(name,","),
1370         length = parse_num(commasplit[1]),
1371         xdash = str_split(commasplit[0], "-x"),
1372         type = xdash[0],
1373         thread = parse_float(xdash[1])
1374    )
1375    assert(len(commasplit)<=2, str("More than one comma found in screw name, \"",name,"\""))
1376    assert(len(xdash)<=2, str("Screw name has too many '-' or 'x' characters, \"",name,"\""))
1377    assert(len(commasplit)==1 || is_num(length), str("Invalid length \"", commasplit[1],"\" in screw name, \"",name,"\""))
1378    assert(len(xdash)==1 || all_nonnegative(thread),str("Thread pitch not a valid number in screw name, \"",name,"\""))
1379    type[0] == "M" || type[0] == "m" ? 
1380        let(diam = parse_float(substr(type,1)))
1381        assert(is_num(diam), str("Screw size must be a number in screw name, \"",name,"\""))
1382        ["metric", parse_float(substr(type,1)), thread, length] 
1383    :
1384    let(
1385        diam = type[0] == "#" ? type :
1386               suffix(type,2)=="''" ? parse_float(substr(type,0,len(type)-2)) :
1387               let(val=parse_num(type))
1388               assert(all_positive(val), str("Screw size must be a number in screw name, \"",name,"\""))
1389               val == floor(val) && val>=0 && val<=12 ? str("#",type) : val
1390    )
1391    assert(is_str(diam) || is_num(diam), str("Invalid screw diameter in screw name, \"",name,"\""))
1392    ["english", diam, thread, u_mul(25.4,length)];
1393
1394
1395// drive can be "hex", "phillips", "slot", "torx", or "none"
1396// or you can specify "ph0" up to "ph4" for phillips and "t20" for torx 20
1397function _parse_drive(drive=undef, drive_size=undef) =
1398    is_undef(drive) ? ["none",undef] 
1399  : assert(is_string(drive))
1400    let(drive = downcase(drive))
1401    in_list(drive,["hex","phillips", "slot", "torx", "phillips", "none"]) ? [drive, drive_size] 
1402  : drive[0]=="t" ? let(size = parse_int(substr(drive,1))) ["torx",size,torx_depth(size) ] 
1403  : starts_with(drive,"ph") && search(drive[2], "01234")!=[] ? ["phillips", ord(drive[2])-ord("0")] 
1404  : assert(false,str("Unknown screw drive type ",drive));
1405
1406
1407// Module: screw_head()
1408// Synopsis: Creates a screw head.
1409// SynTags: Geom
1410// Topics: Threading, Screws
1411// See Also: screw(), screw_hole()
1412// Usage:
1413//    screw_head(screw_info, [details],[counterbore],[flat_height],[teardrop],[internal])
1414// Description:
1415//    Draws the screw head described by the data structure `screw_info`, which
1416//    should have the fields produced by {{screw_info()}}.  See that function for
1417//    details on the fields.  Standard orientation is with the head centered at (0,0)
1418//    and oriented in the +z direction.  Flat heads appear below the xy plane.
1419//    Other heads appear sitting on the xy plane.  
1420// Arguments:
1421//    screw_info = structure produced by {{screw_info()}}
1422//    ---
1423//    details = true for more detailed model.  Default: false
1424//    counterbore = counterbore height.  Default: no counterbore
1425//    flat_height = height of flat head
1426//    teardrop = if true make flathead and counterbores teardrop shaped with the flat 5% away from the edge of the screw.  If numeric, specify the fraction of extra to add.  Set to "max" for a pointed teardrop.  Default: false
1427//    slop = enlarge diameter by this extra amount (beyond that specified in the screw specification).  Default: 0
1428function screw_head(screw_info,details=false, counterbore=0,flat_height,teardrop=false,slop=0) = no_function("screw_head");
1429module screw_head(screw_info,details=false, counterbore=0,flat_height,teardrop=false,slop=0) {
1430   no_children($children);
1431   head_oversize = struct_val(screw_info, "head_oversize",0) + slop;
1432   head = struct_val(screw_info, "head");
1433   head_size = struct_val(screw_info, "head_size",0) + head_oversize;
1434   head_height = struct_val(screw_info, "head_height");
1435   dum0=assert(is_def(head_height) || in_list(head,["flat","none"]), "Undefined head height only allowed with flat head or headless screws")
1436        assert(is_bool(teardrop) || teardrop=="max" || all_nonnegative([teardrop]),"Teardrop parameter invalid");
1437   teardrop = teardrop==true ? .05 : teardrop;
1438   heightok = (is_undef(head_height) && in_list(head,["flat","none"])) || all_positive(head_height);
1439   dum1=assert(heightok, "Head hight must be a postive number");
1440   dum2=assert(counterbore==0 || counterbore==false || head!="none", "Cannot counterbore a headless screw");
1441   counterbore_temp = counterbore==false? 0 
1442                    : head!="flat" && counterbore==true ? head_height 
1443                    : counterbore;
1444   dum3=assert(is_finite(counterbore_temp) && counterbore_temp>=0, str(counterbore==true? "Must specify numerical counterbore height with flat head screw"
1445                                                             : "Counterbore must be a nonnegative number"));
1446
1447   counterbore = counterbore_temp==0 && head!="flat" ? counterbore_temp : counterbore_temp + 0.01;
1448   adj_diam = struct_val(screw_info, "diameter") + head_oversize;   // Used for determining chamfers and ribbing
1449   attachable(){
1450     union(){
1451         if (head!="flat" && counterbore>0){
1452           d = head=="hex"? 2*head_size/sqrt(3) : head_size;
1453           if (teardrop!=false)
1454             teardrop(d=d, l=counterbore, cap_h=is_num(teardrop) ? d/2*(1+teardrop):undef, orient=BACK, anchor=BACK);
1455           else                    
1456             cyl(d=d, l=counterbore, anchor=BOTTOM);
1457         }  
1458         if (head=="flat") {   // For flat head, counterbore is integrated
1459           angle = struct_val(screw_info, "head_angle")/2;
1460           sharpsize = struct_val(screw_info, "head_size_sharp")+head_oversize;
1461           sidewall_height = (sharpsize - head_size)/2 / tan(angle);
1462           cylheight = counterbore + sidewall_height;
1463           slopeheight = flat_height - sidewall_height;
1464           r1 = head_size/2;
1465           r2 = r1 - tan(angle)*slopeheight;
1466           n = segs(r1);
1467           prof1 = teardrop!=false ? teardrop2d(r=r1,cap_h=is_num(teardrop)?r1*(1+teardrop):undef,$fn=n) : circle(r=r1, $fn=n);
1468           prof2 = teardrop!=false ? teardrop2d(r=r2,cap_h=is_num(teardrop)?r2*(1+teardrop):undef,$fn=n) : circle(r=r2, $fn=n);
1469           skin([prof2,prof1,prof1], z=[-flat_height, -flat_height+slopeheight, counterbore],slices=0);
1470         }
1471         if (head!="flat" && counterbore==0) {
1472           if (in_list(head,["round","pan round","button","fillister","cheese"])) {
1473             base = head=="fillister" ? 0.75*head_height :
1474                    head=="pan round" ? .6 * head_height :
1475                    head=="cheese" ? .7 * head_height :
1476                    0.1 * head_height;   // round and button
1477             head_size2 = head=="cheese" ?  head_size-2*tan(5)*head_height : head_size; // 5 deg slope on cheese head
1478             segs = segs(head_size);
1479             cyl(l=base, d1=head_size, d2=head_size2,anchor=BOTTOM, $fn=segs)
1480               attach(TOP)
1481                 zrot(180) // Needed to align facets when $fn is odd
1482                 rotate_extrude($fn=segs)  // ensure same number of segments for cap as for head body
1483                   intersection(){
1484                     arc(points=[[-head_size2/2,0], [0,-base+head_height * (head=="button"?4/3:1)], [head_size2/2,0]]);
1485                     square([head_size2, head_height-base]);
1486                   }
1487           }
1488           if (head=="pan flat")
1489             cyl(l=head_height, d=head_size, rounding2=0.2*head_size, anchor=BOTTOM);
1490           if (head=="socket")
1491             cyl(l=head_height, d=head_size, anchor=BOTTOM, chamfer2=details? adj_diam/10:undef);
1492           if (head=="socket ribbed"){
1493             // These numbers are based on ISO specifications that dictate how much oversizsed a ribbed socket head can be
1494             // We are making our ribbed heads the same size as unribbed (by cutting the ribbing away), but these numbers are presumably a good guide
1495             rib_size = [[2, .09],
1496                         [3, .09],
1497                         [6, .11],
1498                         [12, .135],
1499                         [20, .165]];
1500             intersection() {
1501               cyl(h=head_height/4, d=head_size, anchor=BOT)
1502                  attach(TOP) cyl(l=head_height*3/4, d=head_size, anchor=BOT, texture="trunc_ribs", tex_reps=[31,1],
1503                                  tex_inset=true, tex_depth=-lookup(adj_diam,rib_size));
1504               cyl(h=head_height,d=head_size, chamfer2=adj_diam/10, anchor=BOT);
1505             }
1506           }
1507           if (head=="hex")
1508             up(head_height/2)_nutshape(head_size,head_height,"hex",false,true);
1509         }
1510     }    
1511     union(){};
1512   }
1513}
1514
1515
1516// Section: Nuts and nut traps
1517
1518
1519// Module: nut()
1520// Synopsis: Creates a standard nut.
1521// SynTags: Geom
1522// Topics: Threading, Screws
1523// See Also: screw(), screw_hole()
1524// Usage:
1525//   nut([spec], [shape], [thickness], [nutwidth], [thread=], [tolerance=], [hole_oversize=], [bevel=], [$slop=], [anchor=], [spin=], [orient=]) [ATTACHMENTS];
1526// Description:
1527//   Generates a hexagonal or square nut.  See [screw and nut parameters](#section-screw-and-nut-parameters) for details on the parameters that define a nut.
1528//   As with screws, you can give the specification in `spec` and then omit the name.  The diameter is the flat-to-flat
1529//   size of the nut produced.  The thickness can be "thin", "normal" or "thick" to choose standard nut dimensions.  For metric
1530//   nuts you can also use thickness values of "DIN" or "undersized".  The nut's shape is hexagonal by default; set shape to "square" for
1531//   a square nut.
1532//   .
1533//   By default all nuts have the internal holes beveled and hex nuts have their corners beveled.  Square nuts get no outside bevel by default.
1534//   ASME specifies that small square nuts should not be beveled, and many square nuts are beveled only on one side.   The bevel angle, specified with bevang,
1535//   gives the angle for the bevel.  The default of 15 is shallow and may not be printable.  Internal hole are beveled at 45 deg by the depth of one thread.  
1536//   .
1537//   The tolerance determines the actual thread sizing based on the nominal size in accordance with standards.  
1538//   The $slop parameter determines extra gaps left to account for printing overextrusion.  It defaults to 0.
1539// Arguments:
1540//   spec = nut specification, e.g. "M5x1" or "#8-32".  See [screw naming](#subsection-screw-naming).  This can also be a nut or screw specification structure of the form produced by {{nut_info()}} or {{screw_info()}}.  
1541//   shape = "hex" or "square" to specify nut shape.  Default: "hex"
1542//   thickness = "thin", "normal", "thick", or a thickness in mm.  See [nuts](#subsection-nuts).  Default: "normal"
1543//   ---
1544//   nutwidth = width of nut (overrides table values)
1545//   thread = thread type or specification. See [screw pitch](#subsection-standard-screw-pitch). Default: "coarse"
1546//   hole_oversize = amount to increase hole diameter.  Default: 0
1547//   bevel = if true, bevel the outside of the nut.  Default: true for hex nuts, false for square nuts
1548//   bevel1 = if true, bevel the outside of the nut bottom.
1549//   bevel2 = if true, bevel the outside of the nut top. 
1550//   bevang = set the angle for the outside nut bevel.  Default: 15
1551//   ibevel = if true, bevel the inside (the hole).   Default: true
1552//   ibevel1 = if true bevel the inside, bottom end.
1553//   ibevel2 = if true bevel the inside, top end.
1554//   blunt_start = If true apply truncated blunt start threads at both ends.  Default: true
1555//   blunt_start1 = If true apply truncated blunt start threads bottom end.
1556//   blunt_start2 = If true apply truncated blunt start threads top end.
1557//   tolerance = nut tolerance.  Determines actual nut thread geometry based on nominal sizing.  See [tolerance](#subsection-tolerance). Default is "2B" for UTS and "6H" for ISO.
1558//   $slop = extra space left to account for printing over-extrusion.  Default: 0
1559//   anchor = Translate so anchor point is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `CENTER`
1560//   spin = Rotate this many degrees around the Z axis after anchor.  See [spin](attachments.scad#subsection-spin).  Default: `0`
1561//   orient = Vector to rotate top towards, after spin.  See [orient](attachments.scad#subsection-orient).  Default: `UP`
1562// Side Effects:
1563//   `$screw_spec` is set to the spec specification structure. 
1564// Example: All the UTS nuts at one size.  Note that square nuts come in only one thickness.  
1565//   xdistribute(spacing=0.75*INCH){
1566//       nut("3/8",thickness="thin");
1567//       nut("3/8",thickness="normal");
1568//       nut("3/8",thickness="thick");
1569//       nut("3/8",shape="square");
1570//   }
1571// Example: All the ISO (and DIN) nuts at one size.  Note that M10 is one of the four cases where the DIN nut width is larger.  
1572//   ydistribute(spacing=30){
1573//      xdistribute(spacing=22){
1574//         nut("M10", thickness="thin");
1575//         nut("M10",thickness="undersized");
1576//         nut("M10",thickness="normal");
1577//         nut("M10",thickness="thick");
1578//      }
1579//      xdistribute(spacing=25){
1580//         nut("M10", shape="square", thickness="thin");
1581//         nut("M10", shape="square", thickness="normal");      
1582//      }
1583//   }
1584// Example: The three different UTS nut tolerances (thickner than normal nuts)
1585//   module mark(number)
1586//   {
1587//     difference(){
1588//        children();
1589//        ycopies(n=number, spacing=1.5)right(.25*INCH-2)up(8-.35)cyl(d=1, h=1);
1590//     }
1591//   }
1592//   $fn=64;
1593//   xdistribute(spacing=17){
1594//     mark(1) nut("1/4-20", thickness=8, nutwidth=0.5*INCH,tolerance="1B");
1595//     mark(2) nut("1/4-20", thickness=8, nutwidth=0.5*INCH,tolerance="2B");
1596//     mark(3) nut("1/4-20", thickness=8, nutwidth=0.5*INCH,tolerance="3B");
1597//   }
1598// Example: Threadless nut
1599//   nut("#8", thread="none");
1600
1601function nut(spec, shape, thickness, nutwidth, thread, tolerance, hole_oversize, 
1602           bevel,bevel1,bevel2,bevang=15,ibevel,ibevel1,ibevel2,blunt_start, blunt_start1, blunt_start2, anchor=BOTTOM, spin=0, orient=UP, oversize=0)
1603           = no_function("nut");
1604module nut(spec, shape, thickness, nutwidth, thread, tolerance, hole_oversize, 
1605           bevel,bevel1,bevel2,bevang=15,ibevel,ibevel1,ibevel2,blunt_start, blunt_start1, blunt_start2, anchor=BOTTOM, spin=0, orient=UP, oversize=0)
1606{
1607   dummyA = assert(is_undef(nutwidth) || (is_num(nutwidth) && nutwidth>0));
1608   
1609   tempspec = _get_spec(spec, "nut_info", "nut", 
1610                        thread=thread, shape=shape, thickness=thickness);
1611   spec=_struct_reset(tempspec,[
1612                                ["width", nutwidth],
1613                                ["shaft_oversize", hole_oversize],
1614                               ]);
1615   dummy=_validate_nut_spec(spec);
1616   $screw_spec = spec;
1617   shape = struct_val(spec, "shape");
1618   pitch =  struct_val(spec, "pitch") ;
1619   threadspec = pitch==0 ? undef : thread_specification(spec, internal=true, tolerance=tolerance);
1620   nutwidth = struct_val(spec, "width");
1621   thickness = struct_val(spec, "thickness");
1622   threaded_nut(
1623        nutwidth=nutwidth,
1624        id=pitch==0 ? _nominal_diam(spec)
1625          : [mean(struct_val(threadspec, "d_minor")),
1626             mean(struct_val(threadspec, "d_pitch")),
1627             mean(struct_val(threadspec, "d_major"))],
1628        pitch = pitch, 
1629        h=thickness,
1630        shape=shape, 
1631        bevel=bevel,bevel1=bevel1,bevel2=bevel2,bevang=bevang,
1632        ibevel=ibevel,ibevel1=ibevel1,ibevel2=ibevel2,
1633        blunt_start=blunt_start, blunt_start1=blunt_start1, blunt_start2=blunt_start2,         
1634        anchor=anchor,spin=spin,orient=orient) children();
1635}
1636
1637
1638
1639
1640
1641
1642// Module: nut_trap_side()
1643// Synopsis: Creates a side nut trap mask.
1644// SynTags: Geom
1645// Topics: Threading, Screws
1646// See Also: screw(), screw_hole()
1647// Usage:
1648//   nut_trap_side(trap_width, [spec], [shape], [thickness], [nutwidth=], [poke_len=], [poke_diam=], [$slop=], [anchor=], [orient=], [spin=]) [ATTACHMENTS];
1649// Description:
1650//   Create a nut trap that extends sideways, so the nut slides in perpendicular to the screw axis.
1651//   The CENTER anchor is the center of the screw hole location in the trap.  The trap width is
1652//   measured from the screw hole center point.  You can optionally create a poke hole to use for
1653//   removing the nut by specifying a poke_len value that determines the length of the poke hole, measured
1654//   from the screw center.  The diameter of the poke hole defaults to the thickness of the nut.  The nut dimensions
1655//   will be increased by `2*$slop` to allow adjusting the fit of the trap for your printer.  
1656//   The trap will have a default tag of "remove" if no other tag is in force.  
1657// Arguments:
1658//   trap_width = width of nut trap, measured from screw center, must be larger than half the nut width  (If spec is omitted this argument must be given by name.)
1659//   spec = nut specification, e.g. "M5" or "#8".  See [screw naming](#subsection-screw-naming).  This can also be a screw or nut specification structure of the form produced by {{nut_info()}} or {{screw_info()}}.  
1660//   shape = "hex" or "square" to specify the shape of the nut.   Default: "hex"
1661//   thickness = "thin", "normal", or "thick".  "DIN" or "undersized" for metric nuts.  See [nuts](#subsection-nuts). Default: "normal"
1662//   ---
1663//   nutwidth = width of the nut.  Default: determined from tables
1664//   poke_len = length of poke hole.  Default: no poke hole
1665//   poke_diam = diameter of poke hole.  Default: nut thickness
1666//   $slop = extra space left to account for printing over-extrusion.  Default: 0
1667//   anchor = Translate so anchor point is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `BOTTOM`
1668//   spin = Rotate this many degrees around the Z axis after anchor.  See [spin](attachments.scad#subsection-spin).  Default: `0`
1669//   orient = Vector to rotate top towards, after spin.  See [orient](attachments.scad#subsection-orient).  Default: `UP`
1670// Side Effects:
1671//   `$screw_spec` is set to the spec specification structure. 
1672// Example: Basic trap.  Note that screw center is at the origin and the width is measured from the origin.  
1673//   nut_trap_side(10, "#8");
1674// Example: Trap with poke hole for removing nut.  The poke hole length is also measured from the screw center at the origin
1675//   $fn=16;
1676//   nut_trap_side(10, "#8", poke_len=10);
1677// Example: Trap for square nut
1678//   $fn=16;
1679//   nut_trap_side(10, "#8", shape="square", poke_len=10);
1680// Example: Trap with looser fit
1681//   nut_trap_side(10, "#8", $slop=0.1);
1682// Example: Trap placed at the bottom of a screw hole
1683//   $fn=24;
1684//   screw_hole("#8,1") 
1685//     position(BOT) nut_trap_side(10,poke_len=8);
1686// Example: Trap placed at the bottom of a screw hole 2mm extra screw hole below the trap
1687//   $fn=24;
1688//   screw_hole("#8,1") 
1689//     up(2) position(BOT) nut_trap_side(trap_width=10,poke_len=8);
1690// Example: Hole-trap assembly removed from an object
1691//   $fn=24;
1692//   back_half()
1693//   diff()
1694//   cuboid(30)
1695//      position(TOP)screw_hole("#8,1",anchor=TOP) 
1696//        position(BOT) nut_trap_side(trap_width=16);
1697// Example: Hole-trap assembly where we position the trap relative to a feature on the model and then position the screw hole through the trap as a child to the trap.  
1698//  diff()
1699//   cuboid([30,30,20])
1700//     position(RIGHT)cuboid([4,20,3],anchor=LEFT)
1701//       right(1)position(TOP+LEFT)nut_trap_side(15, "#8",anchor=BOT+RIGHT)
1702//         screw_hole(length=20,anchor=BOT);
1703module nut_trap_side(trap_width, spec, shape, thickness, nutwidth, anchor=BOT, orient, spin, poke_len=0, poke_diam) {
1704  dummy9=assert(is_num(trap_width), "trap_width is missing or the wrong type");
1705  tempspec = _get_spec(spec, "nut_info", "nut_trap", shape=shape, thickness=thickness);
1706  nutdata = _struct_reset(tempspec, [["width", nutwidth]]);
1707  $screw_spec = is_def(spec) ? nutdata : $screw_spec;
1708  dummy8 = _validate_nut_spec(nutdata);
1709  nutwidth = struct_val(nutdata,"width")+2*get_slop();
1710  dummy = assert(is_num(poke_len) && poke_len>=0, "poke_len must be a nonnegative number")
1711          assert(is_undef(poke_diam) || (is_num(poke_diam) && poke_diam>0), "poke_diam must be a positive number")
1712          assert(is_num(trap_width) && trap_width>=nutwidth/2, str("trap_width is smaller than nut width: ",nutwidth));
1713  nutthickness = struct_val(nutdata, "thickness")+2*get_slop();
1714  cubesize = [trap_width, nutwidth,nutthickness];
1715  halfwidth = shape=="square" ? nutwidth/2 : nutwidth/sqrt(3);
1716  shift = cubesize[0]/2 - halfwidth/2;
1717  default_tag("remove")
1718    attachable(size=cubesize+[halfwidth,0,0], offset=[shift,0,0],anchor=anchor,orient=orient,spin=spin)
1719    {
1720       union(){
1721         if (shape=="square") left(nutwidth/2) cuboid(cubesize+[halfwidth,0,0],anchor=LEFT);
1722         else {
1723            cuboid(cubesize,anchor=LEFT);
1724            linear_extrude(height=nutthickness,center=true)hexagon(id=nutwidth);
1725         }
1726         if (poke_len>0)
1727           xcyl(l=poke_len, d=default(poke_diam, nutthickness), anchor=RIGHT);
1728       }
1729       children();
1730    }     
1731}
1732
1733// Module: nut_trap_inline()
1734// Synopsis: Creates an inline nut trap mask.
1735// SynTags: Geom
1736// Topics: Threading, Screws
1737// See Also: screw(), screw_hole()
1738// Usage:
1739//   nut_trap_inline(length|l|heigth|h, [spec], [shape], [$slop=], [anchor=], [orient=], [spin=]) [ATTACHMENTS];
1740// Description:
1741//   Create a nut trap that extends along the axis of the screw.  The nut width
1742//   will be increased by `2*$slop` to allow adjusting the fit of the trap for your printer.
1743//   If no tag is present the trap will be tagged with "remove".  Note that you can omit the specification
1744//   and it will be inherited from a parent screw_hole to provide the screw size.  It's also possible to 
1745//   do this backwards, to declare a trap at a screw size and make a child screw hole, which will inherit
1746//   the screw dimensions.  
1747// Arguments:
1748//   length/l/height/h = length/height of nut trap
1749//   spec = nut specification, e.g. "M5" or "#8".  See [screw naming](#subsection-screw-naming).  This can also be a screw or nut specification structure of the form produced by {{nut_info()}} or {{screw_info()}}.  
1750//   shape = "hex" or "square to determine type of nut.  Default: "hex"
1751//   ---
1752//   $slop = extra space left to account for printing over-extrusion.  Default: 0
1753//   anchor = Translate so anchor point is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `TOP`
1754//   spin = Rotate this many degrees around the Z axis after anchor.  See [spin](attachments.scad#subsection-spin).  Default: `0`
1755//   orient = Vector to rotate top towards, after spin.  See [orient](attachments.scad#subsection-orient).  Default: `UP`
1756// Side Effects:
1757//   `$screw_spec` is set to the spec specification structure. 
1758// Example: Basic trap
1759//   nut_trap_inline(10, "#8");
1760// Example: Basic trap with allowance for a looser fit
1761//   nut_trap_inline(10, "#8", $slop=.1);
1762// Example: Square trap (just a cube, but hopefully just the right size)
1763//   nut_trap_inline(10, "#8", shape="square");
1764// Example: Attached to a screw hole
1765//   screw_hole("#8,1",head="socket",counterbore=true, $fn=32) 
1766//     position(BOT) nut_trap_inline(10);
1767// Example: Nut trap with child screw hole
1768//   nut_trap_inline(10, "#8")
1769//     position(TOP)screw_hole(length=10,anchor=BOT,head="flat",$fn=32);
1770// Example(Med,NoAxes): a pipe clamp
1771//   $fa=5;$fs=0.5;
1772//   bardiam = 32;
1773//   bandwidth = 10;
1774//   thickness = 3;
1775//   back_half()
1776//   diff()
1777//     tube(id=bardiam, wall = thickness, h=bandwidth, orient=BACK)
1778//       left(thickness/2) position(RIGHT) cube([bandwidth, bandwidth, 14], anchor = LEFT, orient=FWD)
1779//       {
1780//          screw_hole("#4",length=12, head="socket",counterbore=6,anchor=CENTER)
1781//             position(BOT) nut_trap_inline(l=6,anchor=BOT);
1782//          tag("remove")right(1)position(RIGHT)cube([11+thickness, 11, 2], anchor = RIGHT);
1783//       }
1784module nut_trap_inline(length, spec, shape, l, height, h, nutwidth, anchor, orient, spin) {
1785  tempspec = _get_spec(spec, "nut_info", "nut_trap", shape=shape, thickness=undef);
1786  nutdata = _struct_reset(tempspec, [["width", nutwidth]]);
1787  $screw_spec = is_def(spec) ? nutdata : $screw_spec;
1788  dummy = _validate_nut_spec(nutdata);
1789  length = one_defined([l,length,h,height],"l,length,h,height");
1790  assert(is_num(length) && length>0, "length must be a positive number");
1791  nutwidth = struct_val(nutdata,"width")+2*get_slop();
1792  default_tag("remove"){
1793    if (shape=="square")
1794      cuboid([nutwidth,nutwidth,length], anchor=anchor, orient=orient, spin=spin) children();
1795    else
1796      linear_sweep(hexagon(id=nutwidth),height=length, anchor=anchor,orient=orient, spin=spin) children();
1797  }
1798}
1799
1800
1801
1802// Section: Screw and Nut Information
1803
1804
1805// Function: screw_info()
1806// Synopsis: Returns the dimensions and other info for the given screw.
1807// Topics: Threading, Screws
1808// See Also: screw(), screw_hole()
1809// Usage:
1810//   info = screw_info(name, [head], [drive], [thread=], [drive_size=], [oversize=], [head_oversize=])
1811// Description:
1812//   Look up screw characteristics for the specified screw type.
1813//   See [screw and nut parameters](#section-screw-and-nut-parameters) for details on the parameters that define a screw.
1814//   .
1815//   The `oversize=` parameter adds the specified amount to the screw and head diameter to make an
1816//   oversized screw.  Does not affect length, thread pitch or head height.
1817//   .
1818//   Note that flat head screws are defined by two different diameters, the theoretical maximum diameter, "head_size_sharp"
1819//   and the actual diameter, "head_size".  The screw form is defined using the theoretical maximum, which gives
1820//   sharp circular edge at the top of the screw.  Real screws have a flat chamfer around the edge.  
1821// Figure(2D,Med,NoAxes,VPD=39,VPT=[0,-4,0],VPR=[0,0,0]):  Flat head screw geometry
1822//   polysharp = [[0, -5.07407], [4.92593, -5.07407], [10, 0], [10, 0.01], [0, 0.01]];
1823//   color("blue"){
1824//       xflip_copy()polygon(polysharp);
1825//       back(1/2)stroke([[-10,0],[10,0]],endcaps="arrow2",width=.15);    
1826//       back(1.7)text("\"head_size_sharp\"", size=.75,anchor=BACK);
1827//   }
1828//   poly= [[0, -5.07407], [4.92593, -5.07407], [9.02, -0.98], [9.02, 0.01], [0, 0.01]];
1829//   xflip_copy()polygon(poly);
1830//   rect([10,10],anchor=TOP);
1831//   color("black"){
1832//     fwd(1/2)stroke([[-9.02,0],[9.02,0]],endcaps="arrow2",width=.15);
1833//     fwd(1)text("\"head_size\"", size=.75,anchor=BACK);
1834//   }  
1835// Continues:
1836//   The output is a [struct](structs.scad) with the following fields:
1837//   . 
1838//   Field              | What it is
1839//   ------------------ | ---------------
1840//   "type"           | Always set to "screw_info"
1841//   "system"         | Either `"UTS"` or `"ISO"` (used for correct tolerance computation).
1842//   "origin"         | Module that generated the structure
1843//   "name"           | Screw name used to make the structure
1844//   "diameter"       | The nominal diameter of the screw shaft in mm.
1845//   "pitch"          | The thread pitch in mm.  (0 for no threads)
1846//   "head"           | The type of head (a string)
1847//   "head_size"      | Size of the head (usually diameter) in mm.
1848//   "head_size_sharp"| Theoretical head diameter for a flat head screw if it is made with sharp edges (or for countersinks)
1849//   "head_angle"     | Countersink angle for flat heads.
1850//   "head_height"    | Height of the head beyond the screw's nominal length.  The screw's total length is "length" + "head_height".  For flat heads "head_height" is zero, because they do not extend the screw.  
1851//   "drive"          | The drive type (`"phillips"`, `"torx"`, `"slot"`, `"hex"`, `"none"`)
1852//   "drive_size"     | The drive size, either a drive number (phillips, torx) or a dimension in mm (hex, slot).
1853//   "drive_depth"    | Depth of the drive recess.
1854//   "length"         | Length of the screw in mm measured in the customary fashion.  For flat head screws the total length and for other screws, the length from the bottom of the head to the screw tip.
1855//   "thread_len"     | Length of threaded portion of screw in mm
1856//   "shaft_oversize"| Amount to oversize the threads
1857//   "head_oversize"   | Amount to oversize the head
1858//   .
1859//   If you want to define a custom drive for a screw you will need to provide the drive size and drive depth.  
1860//
1861// Arguments:
1862//   name = screw specification, e.g. "M5x1" or "#8-32".  See [screw naming](#subsection-screw-naming).
1863//   head = head type.  See [screw heads](#subsection-screw-heads)  Default: none
1864//   drive = drive type.  See [screw heads](#subsection-screw-heads) Default: none
1865//   ---
1866//   thread = thread type or specification. See [screw pitch](#subsection-standard-screw-pitch). Default: "coarse"
1867//   drive_size = size of drive recess to override computed value
1868//   shaft_oversize = amount to increase screw diameter for clearance holes.  Default: 0
1869//   head_oversize = amount to increase head diameter for countersink holes.  Default: 0 
1870
1871function screw_info(name, head, drive, thread, drive_size, shaft_oversize, head_oversize, _origin) =
1872  assert(is_string(name), "Screw specification must be a string")
1873  let(
1874      thread = is_undef(thread) || thread==true ? "coarse"
1875             : thread==false || thread=="none" ? 0
1876             : thread,
1877      head = default(head,"none"),
1878      type=_parse_screw_name(name),
1879      drive_info = _parse_drive(drive, drive_size),
1880      drive=drive_info[0],
1881      screwdata =   type[0] == "english" ? _screw_info_english(type[1],type[2], head, thread, drive) 
1882                  : type[0] == "metric" ? _screw_info_metric(type[1], type[2], head, thread, drive) 
1883                  : []
1884    )
1885    assert(is_def(struct_val(screwdata,"head")),str("Screw head \"",head,"\" unknown or unsupported for specified screw"))
1886    _struct_reset(screwdata,
1887         [
1888          ["drive_depth", drive_info[2]],
1889          ["length", type[3]],
1890          ["drive_size", drive_info[1]],
1891          ["name", name],
1892          ["shaft_oversize", shaft_oversize],
1893          ["head_oversize", head_oversize],
1894          ["origin",_origin]
1895         ]);
1896      
1897
1898// Function: nut_info()
1899// Synopsis: Returns the dimensions and other info for the given nut.
1900// Topics: Threading, Screws
1901// See Also: screw(), screw_hole()
1902// Usage:
1903//   nut_spec = nut_info(name, [shape], [thickness=], [thread=], [width=], [hole_oversize=]);
1904// Description:
1905//   Produces a nut specification structure that describes a nut.  You can specify the width
1906//   and thickness numerically, or you can let the width be calculated automatically from
1907//   the thread specification.  The thickness can be "normal" (the default) or "thin" or "thick".
1908//   Note that square nuts are only available in "normal" thickness, and "thin" and "thick" nuts
1909//   are only available for 1/4 inch and above.  
1910//   .
1911//   The output is a [struct](structs.scad) with the following fields:
1912//   . 
1913//   Field              | What it is
1914//   ------------------ | ---------------
1915//   "type"           | Always set to "nut_info"
1916//   "system"         | Either `"UTS"` or `"ISO"` (used for correct tolerance computation).
1917//   "origin"         | Module that created the structure
1918//   "name"           | Name used to specify threading, such as "M6" or "#8"
1919//   "diameter"       | The nominal diameter of the screw hole in mm.
1920//   "pitch"          | The thread pitch in mm.  (0 for no threads)
1921//   "shape"          | Shape of the nut, either "hex" or "square"
1922//   "width"          | Flat to flat width of the nut
1923//   "thickness"      | Thickness of the nut
1924//   "shaft_oversize" | amount to oversize the threads (not including $slop)
1925// Arguments:
1926//   name = screw name, e.g. "M5x1" or "#8-32".  See [screw naming](#subsection-screw-naming).
1927//   shape = shape of the nut, either "hex" or "square".  Default: "hex"
1928//   ---
1929//   thread = thread type or specification. See [screw pitch](#subsection-standard-screw-pitch). Default: "coarse"
1930//   thickness = thickness of the nut (in mm) or one of "thin", "normal", or "thick".  Default: "normal"
1931//   width = width of nut in mm.  Default: computed from thread specification
1932//   hole_oversize = amount ot increase diameter of hole in nut.  Default: 0
1933
1934function nut_info(name, shape, thickness, thread, hole_oversize=0, width, _origin) =
1935  assert(is_undef(thickness) || (is_num(thickness) && thickness>0) ||
1936           in_list(_downcase_if_str(thickness),["thin","normal","thick","undersized","din"]),
1937          "thickness must be a positive number of one of \"thin\", \"thick\", \"normal\", \"undersized\", or \"DIN\"")
1938  let(
1939      shape = _downcase_if_str(default(shape,"hex")),
1940      thickness = _downcase_if_str(default(thickness, "normal"))
1941  )
1942  assert(is_string(name), str("Nut nameification must be a string ",name))
1943  assert(in_list(shape, ["hex","square"]), "Nut shape must be \"hex\" or \"square\"")
1944  assert(is_undef(width) || (is_num(width) && width>0), "Specified width must be a positive number")
1945  let(
1946      type = _parse_screw_name(name),
1947      thread = is_undef(thread) || thread==true ? "coarse"
1948             : thread==false || thread=="none" ? 0
1949             : thread,
1950      nutdata = type[0]=="english" ? _nut_info_english(type[1],type[2], thread, shape, thickness, width)
1951              : type[0]=="metric" ?  _nut_info_metric(type[1],type[2], thread, shape, thickness, width)
1952              : []
1953  )
1954  _struct_reset(nutdata, [["name", name],
1955                          ["shaft_oversize",hole_oversize],
1956                          ["width", width],
1957                          ["origin",_origin]
1958                         ]);
1959
1960
1961// Nut data is from ASME B18.2.2, mostly Table A-1
1962function _nut_info_english(diam, threadcount, thread, shape, thickness, width) =
1963  assert(!is_string(thickness) || in_list(thickness,["normal","thin","thick"]),
1964         "You cannot use thickness \"DIN\" or \"undersized\" with English nuts")
1965  let(
1966       screwspec=_screw_info_english(diam, threadcount, head="none", thread=thread),
1967       diameter = struct_val(screwspec,"diameter")/INCH,
1968       //         thickness  width
1969       normal = [
1970            ["#0", [ 3/64 , 5/32  ]],
1971            ["#1", [ 3/64 , 5/32  ]],
1972            ["#2", [ 1/16 , 3/16  ]],
1973            ["#3", [ 1/16 , 3/16  ]],
1974            ["#4", [ 3/32 ,  1/4  ]],
1975            ["#5", [ 7/64 , 5/16  ]],
1976            ["#6", [ 7/64 , 5/16  ]],
1977            ["#8", [  1/8 ,11/32  ]],
1978            ["#10",[  1/8 ,  3/8  ]],
1979            ["#12",[ 5/32 , 7/16  ]],
1980            [1/4,  [ 7/32 , 7/16  ]],
1981       ],
1982       thin = [  // thickness
1983            [1/4,  [ 5/32]],
1984            [5/16, [ 3/16]],
1985            [3/8,  [ 7/32]],
1986            [7/16, [  1/4]],
1987            [1/2,  [ 5/16]],
1988            [9/16, [ 5/16]],
1989            [5/8,  [  3/8]]
1990       ],
1991       thick = [
1992            [1/4,  [9/32 ]],
1993            [5/16, [21/64]],
1994            [3/8,  [13/32]],
1995            [7/16, [29/64]],
1996            [1/2,  [9/16]],
1997            [9/16, [39/64]],
1998            [5/8,  [23/32]],
1999            [3/4,  [13/16]],
2000            [7/8,  [29/32]],
2001            [1,    [1]],
2002            [1+1/8,[1+5/32]],
2003            [1+1/4,[1+1/4]],
2004            [1+3/8,[1+3/8]],
2005            [1+1/2,[1+1/2]]
2006       ]
2007  )
2008  assert(is_num(thickness) || thickness=="normal" || diameter >=1/4,
2009         str("No ", thickness, " nut available at requested thread size"))
2010  assert(diameter <= 1.5, "No thickness available for nut diameter over 1.5 inches")
2011  assert(shape=="hex" || thickness=="normal" || is_num(thickness),"Square nuts only come in normal thickness")
2012  let(
2013      table = thickness=="normal" ? normal
2014            : thickness=="thick" ? thick
2015            : thickness=="thin"  ? thin
2016            : [],
2017      entry = struct_val(table, diam),
2018      thickness = is_num(thickness) ? thickness/INCH
2019                : is_def(entry) ? entry[0]
2020                : shape=="square" ? ( approx(diameter,1.125) ? 1
2021                                                             : quantdn(7/8 * diameter,1/64))
2022                : thickness=="thin" ? (diameter < 1+3/16 ? quantdn(0.5*diameter + 3/64,1/64)
2023                                                         : 0.5*diameter + 3/32)
2024                  // remaining case is "normal" thickness
2025                : diameter < 11/16 ? quantdn(7/8*diameter,1/64)
2026                : diameter < 1+3/16 ? 7/8*diameter - 1/64
2027                : 7/8 * diameter - 1/32, 
2028      width = is_num(width) ? width/INCH
2029            : is_def(entry[1]) ? entry[1]
2030            : shape=="square" ? (diameter<5/8 ? quantup(1.5*diameter,1/16)+1/16 : 1.5*diameter)
2031            : quantup(1.5*diameter,1/16)
2032  )
2033  [["type","nut_info"],
2034   ["system", "UTS"],
2035   ["diameter", struct_val(screwspec, "diameter")],
2036   ["pitch", struct_val(screwspec,"pitch")],
2037   ["width", width*INCH],
2038   ["thickness", thickness*INCH],
2039   ["shape", shape]];
2040
2041
2042function _downcase_if_str(s) = is_string(s) ? downcase(s) : s;
2043
2044function _nut_info_metric(diam, pitch, thread, shape, thickness, width) =
2045  let(
2046       screwspec=_screw_info_metric(diam, pitch, head="none", thread=thread),
2047       diameter = struct_val(screwspec,"diameter"),
2048
2049       ISO_table =      //     - ASME B18.4.1M -    DIN 439
2050          //                   --- ISO 4032 ----   ISO 4035   ISO 4033 
2051          //                   normal     normal     thin       thick
2052          // diam    width     midpt      max        (max)      (max)
2053          // Preferred threads
2054          [
2055             [1.6,   [3.2 ,     1.2,       1.3,       1.0   ]],
2056             [2,     [4   ,     1.5,       1.6,       1.2   ]],
2057             [2.5,   [5   ,     1.875,     2,         1.6   ]],
2058             [3,     [5.5 ,     2.25,      2.4,       1.8   ]],
2059             [4,     [7   ,     3,         3.2,       2.2   ]],
2060             [5,     [8   ,     4.5 ,      4.7,       2.7,      5.1]],
2061             [6,     [10  ,     5,         5.2,       3.2,      5.7]],
2062             [8,     [13  ,     6.675,     6.8,      undef,      7.5]],
2063             [10,    [16  ,     8.25,      8.4,      undef,      9.3]],
2064             [12,    [18  ,     10.5,     10.8,      undef,     12  ]],
2065             [16,    [24  ,     14.5,     14.8,      undef,     16.4]],
2066             [20,    [30  ,     17.5,     18,        undef,     20.3]],
2067             [24,    [36  ,     21,       21.5,      undef,     23.9]],
2068             [30,    [46  ,     25,       25.6,      undef,     28.6]],
2069             [36,    [55  ,     30,       31,        undef,     34.7]],
2070             [42,    [65  ,     33,       34,        undef      ]],
2071             [48,    [75  ,     37,       38,        undef      ]],
2072             [56,    [85  ,     44,       45,        undef      ]],
2073             [64,    [95  ,     50,       51,        undef      ]],
2074          // Non-preferred threads
2075             [3.5,   [ 6,       2.675,     2.8,      2          ]],
2076             [14,    [21,      12.5,      12.8,      undef,     14.1]],
2077             [18,    [27,      15.5,      15.8,      undef,     17.6]],
2078             [22,    [34,      19,        19.4,      undef,     21.8]],
2079             [27,    [41,      23,        23.8,      undef,     26.7]],
2080             [33,    [50,      28,        28.7,      undef,     32.5]],
2081             [39,    [60,      33,        33.4,      undef      ]],
2082             [45,    [70,      35,        36,        undef      ]],
2083             [52,    [80,      41,        42,        undef      ]],
2084             [60,    [90,      47,        48,        undef      ]]
2085          ],
2086       DIN_table =
2087          [
2088             //                  DIN 934   DIN 936  DIN 562     DIN 557
2089             //diam      width   normal    thin    thin square   square
2090             [   1,    [   2.5,    0.8,   undef]],
2091             [   1.2,  [   3,      1  ,   undef]],
2092             [   1.4,  [   3,      1.2,   undef]],
2093             [   1.6,  [   3.2,    1.3,   undef,      1.0]],
2094             [   2,    [   4,      1.6,   undef,      1.2]],
2095             [   2.5,  [   5,      2  ,   undef,      1.6]],
2096             [   3,    [   5.5,    2.4,   undef,      1.8]],
2097             [   3.5,  [   6,      2.8,   undef,      2.0]],
2098             [   4,    [   7,      3.2,     2.8,      2.2]],
2099             [   5,    [   8,      4,       3.5,      2.7]],
2100             [   6,    [  10,      5,       4  ,      3.2]],
2101             [   7,    [  11,      5.5,     4  ]],
2102             [   8,    [  13,      6.5,     5        ]],
2103             [  10,    [  17,      8,       6        ]],     //
2104             [  12,    [  19,     10,       7  ]],  //
2105             [  14,    [  22,     11,       8  ]],  //
2106             [  16,    [  24,     13,       8  ]],
2107             [  18,    [  27,     15,       9  ]],
2108             [  20,    [  30,     16,       9  ]],
2109             [  22,    [  32,     18,      10  ]],  //
2110             [  24,    [  36,     19,      10  ]],
2111             [  27,    [  41,     22,      12  ]],
2112             [  30,    [  46,     24,      12  ]],
2113             [  33,    [  50,     26,      14  ]],
2114             [  36,    [  55,     29,      14  ]],
2115             [  39,    [  60,     31,      16  ]],
2116             [  42,    [  65,     34,      16  ]],
2117             [  45,    [  70,     36,      18  ]],
2118             [  48,    [  75,     38,      18  ]],
2119             [  52,    [  80,     42,      20  ]],
2120             [  56,    [  85,     45]],
2121             [  60,    [  90,     48]],
2122             [  64,    [  95,     51]],
2123             [  68,    [ 100,     54]],
2124             [  72,    [ 105,     58]],
2125             [  76,    [ 110,     61]],
2126             [  80,    [ 115,     64]],
2127             [  85,    [ 120,     68]],
2128             [  90,    [ 130,     72]],
2129             [ 100,    [ 145,     80]],
2130             [ 110,    [ 155,     88]],
2131             [ 125,    [ 180,    100]],
2132             [ 140,    [ 200,    112]],
2133             [ 160,    [ 230,    128]]
2134          ],
2135          useDIN = thickness=="din" || thickness=="undersized" || shape=="square", 
2136          entry = struct_val(useDIN ? DIN_table : ISO_table, diameter),
2137          width = is_def(width) ? width
2138                : entry[0],
2139          thickind = useDIN && thickness=="thin" ? 3
2140                   : useDIN ? 1 
2141                   : thickness=="normal" ? 2
2142                   : thickness=="thin" ? 3
2143                   : thickness=="thick" ? 4
2144                   : undef,
2145          thickness = is_num(thickness) ? thickness
2146                    : is_def(entry[thickind]) ? entry[thickind]
2147                    : thickness=="thin" && diameter > 8 ? diam/2
2148                    : undef
2149  )
2150  assert(is_def(thickness) && is_def(width), "Unknown thickness, size and shape combination for nut")
2151  [["type","nut_info"],
2152   ["system", "ISO"],
2153   ["diameter", struct_val(screwspec, "diameter")],
2154   ["pitch", struct_val(screwspec,"pitch")],
2155   ["width", width],
2156   ["thickness", thickness],
2157   ["shape", shape]];
2158          
2159
2160function _screw_info_english(diam, threadcount, head, thread, drive) =
2161 let(
2162   diameter = is_string(diam) ? parse_int(substr(diam,1))*0.013 +0.06 
2163                              : diam,
2164   diamgroup = diameter<7/16 ? 0
2165             : diameter==7/16 ? 1
2166             : 2,
2167   pitch =
2168     is_num(thread) ? thread :
2169     is_def(threadcount) ? INCH/threadcount :
2170     let(
2171        tind=struct_val([["coarse",0],["unc",0],
2172                         ["fine",1],["unf",1],
2173                         ["extra fine",2],["extrafine",2],["unef",2]],
2174                         downcase(thread)),
2175        dummy = assert(is_def(tind), str("Unknown thread type, \"",thread,"\"")),
2176                 // coarse  fine  xfine
2177                 // UNC     UNF   UNEF
2178        UTS_thread = [
2179            ["#0", [undef,    80, undef]],
2180            ["#1", [   64,    72, undef]],
2181            ["#2", [   56,    64, undef]],
2182            ["#3", [   48,    56, undef]],
2183            ["#4", [   40,    48, undef]],
2184            ["#5", [   40,    44, undef]],
2185            ["#6", [   32,    40, undef]],
2186            ["#8", [   32,    36, undef]],
2187            ["#10",[   24,    32, undef]],
2188            ["#12",[   24,    28,    32]],
2189            [1/4,  [   20,    28,    32]],
2190            [5/16, [   18,    24,    32]],
2191            [3/8,  [   16,    24,    32]],
2192            [7/16, [   14,    20,    28]],
2193            [1/2,  [   13,    20,    28]],
2194            [9/16, [   12,    18,    24]],
2195            [5/8,  [   11,    18,    24]],
2196            [3/4,  [   10,    16,    20]],
2197            [7/8,  [    9,    14,    20]],
2198            [1,    [    8,    12,    20]],
2199            [1.125,[    7,    12,    18]],
2200            [1.25, [    7,    12,    18]],
2201            [1.375,[    6,    12,    18]],
2202            [1.5,  [    6,    12,    18]],
2203            [1.75, [    5, undef, undef]],
2204            [2,    [  4.5, undef, undef]],
2205         ],
2206       tentry = struct_val(UTS_thread, diam)
2207     )
2208     assert(is_def(tentry), str("Unknown screw size, \"",diam,"\""))
2209     assert(is_def(tentry[tind]), str("No ",thread," pitch known for screw size, \"",diam,"\""))
2210     INCH / tentry[tind],
2211   head_data =
2212       head=="none" ? let (
2213          UTS_setscrew = [
2214               // hex width, hex depth torx,  torx depth    slot width   slot depth 
2215            ["#0", [0.028,   0.050,   undef,     undef,       0.012,       0.018]],
2216            ["#1", [0.035,   0.060,   undef,     undef,       0.014,       0.018]],
2217            ["#2", [0.035,   0.060,   undef,     undef,       0.016,       0.022]],
2218            ["#3", [0.05 ,   0.070,   undef,     undef,       0.018,       0.025]],
2219            ["#4", [0.05 ,   0.045,      6,      0.027,       0.021,       0.028]],
2220            ["#5", [1/16 ,   0.080,      7,      0.036,       0.023,       0.031]],
2221            ["#6", [1/16 ,   0.080,      7,      0.036,       0.025,       0.035]],
2222            ["#8", [5/64 ,   0.090,      8,      0.041,       0.029,       0.041]],
2223            ["#10",[3/32 ,   0.100,      10,     0.049,       0.032,       0.048]],
2224            ["#12",[undef,   undef,   undef,    undef,        0.038,       0.056]],
2225            [1/4,  [1/8  ,   0.125,      15,     0.068,       0.045,       0.063]],
2226            [5/16, [5/32 ,   0.156,      25,     0.088,       0.051,       0.078]],
2227            [3/8,  [3/16 ,   0.188,      30,     0.097,       0.064,       0.094]],
2228            [7/16, [7/32 ,   0.219,      40,     0.117,       0.072,       0.109]],
2229            [1/2,  [1/4  ,   0.250,      45,     0.137,       0.081,       0.125]],
2230            [9/16, [undef,   undef,   undef,    undef,        0.091,       0.141]],
2231            [5/8,  [5/16 ,   0.312,      55,     0.202,       0.102,       0.156]],
2232            [3/4,  [3/8  ,   0.375,      60,     0.202,       0.129,       0.188]],
2233            [7/8,  [1/2  ,   0.500,      70,     0.291]],     
2234            [1,    [9/16 ,   0.562,      70,     0.291]],     
2235            [1.125,[9/16 ,   0.562]],
2236            [1.25, [5/8  ,   0.625]],
2237            [1.375,[5/8  ,   0.625]],
2238            [1.5,  [3/4  ,   0.750]],
2239            [1.75, [1    ,   1.000]],
2240            [2,    [1    ,   1.000]],
2241            ],
2242          entry = struct_val(UTS_setscrew, diam),
2243          dummy=assert(is_def(entry), str("Screw size ",diam," unsupported for headless screws")),
2244          drive_dims = drive == "hex" ? [["drive_size", INCH*entry[0]], ["drive_depth", INCH*entry[1]]]
2245                     : drive == "torx" ? [["drive_size", entry[2]], ["drive_depth", INCH*entry[3]]] 
2246                     : drive == "slot" ? [["drive_size", INCH*entry[4]], ["drive_depth", INCH*entry[5]]]
2247                     : []
2248         ) concat([["head","none"]], drive_dims) 
2249     : head=="hex" ? let( 
2250            UTS_hex = [
2251               // flat to flat width, height
2252               ["#2", [    1/8,   1/16]],
2253               ["#4", [   3/16,   1/16]],
2254               ["#6", [    1/4,   3/32]],
2255               ["#8", [    1/4,   7/64]],
2256               ["#10",[   5/16,    1/8]],
2257               ["#12",[   5/16,   5/32]],
2258               [1/4,  [   7/16,   5/32]],
2259               [5/16, [    1/2,  13/64]],
2260               [3/8,  [   9/16,    1/4]],
2261               [7/16, [    5/8,  19/64]],
2262               [1/2,  [    3/4,  11/32]],
2263               [9/16, [  13/16,  23/64]],
2264               [5/8,  [  15/16,  27/64]],
2265               [3/4,  [  1.125,    1/2]],
2266               [7/8,  [ 1+5/16,  37/64]],
2267               [1,    [    1.5,  43/64]],
2268               [1.125,[1+11/16,  11/16]],
2269               [1.25, [  1+7/8,  27/32]],
2270               [1.5,  [   2.25,  15/16]],
2271               [1.75, [  2+5/8, 1+3/32]],
2272               [2,    [      3, 1+7/32]],
2273            ],
2274            entry = struct_val(UTS_hex, diam)
2275           )
2276           assert(is_def(entry), str("Screw size ",diam," unsupported for head type \"",head,"\""))
2277           [["head", "hex"], ["head_size", INCH*entry[0]], ["head_height", INCH*entry[1]]] 
2278     : in_list(head,["socket","socket ribbed"]) ? let(
2279            UTS_socket = [    // height = screw diameter
2280                       //diam,   hex, torx size, hex depth, torx depth
2281               ["#0", [  0.096,  0.05, 6,         0.025,      0.027]],
2282               ["#1", [  0.118,  1/16, 7,         0.031,      0.036]],
2283               ["#2", [   9/64,  5/64, 8,         0.038,      0.037]],
2284               ["#3", [  0.161,  5/64, 8,         0.044,      0.041]],   // For larger sizes, hex recess depth is
2285               ["#4", [  0.183,  3/32, 10,        0.051,      0.049]],   // half the screw diameter
2286               ["#5", [  0.205,  3/32, 10,        0.057,      0.049]],
2287               ["#6", [  0.226,  7/64, 15,        0.064,      0.058]],
2288               ["#8", [  0.270,  9/64, 25,        0.077,      0.078]],
2289               ["#10",[   5/16,  5/32, 27,        undef,      0.088]],
2290               ["#12",[  0.324,  5/32, 27,        undef,      0.088]],
2291               [1/4,  [    3/8,  3/16, 30,        undef,      0.097]],
2292               [5/16, [  15/32,   1/4, 45,        undef,      0.137]],
2293               [3/8,  [   9/16,  5/16, 50,        undef,      0.155]],
2294               [7/16, [  21/32,   3/8, 55,        undef,      0.202]],
2295               [1/2,  [    3/4,   3/8, 55,        undef,      0.202]],
2296               [9/16, [  27/32,  7/16, 60,        undef,      0.240]],
2297               [5/8,  [  15/16,   1/2, 70,        undef,      0.291]],
2298               [3/4,  [  1.125,   5/8, 80,        undef,      0.332]],
2299               [7/8,  [ 1+5/16,   3/4, 100,       undef,      0.425]],
2300               [1,    [    1.5,   3/4, 100,       undef,      0.425]],
2301               [1.125,[1+11/16,   7/8, undef,     undef,      undef]],
2302               [1.25, [  1+7/8,   7/8, undef,     undef,      undef]],
2303               [1.375,[ 2+1/16,     1, undef,     undef,      undef]],
2304               [1.5,  [   2.25,     1, undef,     undef,      undef]],
2305               [1.75, [  2+5/8,  1.25, undef,     undef,      undef]],
2306               [2,    [      3,   1.5, undef,     undef,      undef]],
2307            ],
2308            entry = struct_val(UTS_socket, diam),
2309            dummy=assert(is_def(entry), str("Screw size ",diam," unsupported for head type \"",head,"\"")),
2310            hexdepth = is_def(entry[3]) ? entry[3]
2311                     : is_def(diameter) ? diameter/2
2312                     : undef,
2313            drive_size =  drive=="hex" ? [["drive_size",INCH*entry[1]], ["drive_depth",INCH*hexdepth]] :
2314                          drive=="torx" ? [["drive_size",entry[2]],["drive_depth",INCH*entry[4]]] : []
2315            )
2316            concat([["head",head],["head_size",INCH*entry[0]], ["head_height", INCH*diameter]],drive_size) 
2317     : head=="pan" ? let (
2318           UTS_pan = [  // pan head for phillips or slotted
2319                 //              head height 
2320                 //    diam,   slotted  phillips  phillips drive, phillips diam, phillips width, phillips depth, slot width, slot depth  torx size
2321               ["#0", [0.116,   0.039,   0.044,        0,          0.067,          0.013,           0.039,       0.023,         0.022]],
2322               ["#1", [0.142,   0.046,   0.053,        0,          0.085,          0.015,           0.049,       0.027,         0.027]],
2323               ["#2", [0.167,   0.053,   0.063,        1,          0.104,          0.017,           0.059,       0.031,         0.031,      8]],
2324               ["#3", [0.193,   0.060,   0.071,        1,          0.112,          0.019,           0.068,       0.035,         0.036]],
2325               ["#4", [0.219,   0.068,   0.080,        1,          0.122,          0.019,           0.078,       0.039,         0.040,     10]],
2326               ["#5", [0.245,   0.075,   0.089,        2,          0.158,          0.028,           0.083,       0.043,         0.045]],
2327               ["#6", [0.270,   0.082,   0.097,        2,          0.166,          0.028,           0.091,       0.048,         0.050,     15]],
2328               ["#8", [0.322,   0.096,   0.115,        2,          0.182,          0.030,           0.108,       0.054,         0.058,     20]],
2329               ["#10",[0.373,   0.110,   0.133,        2,          0.199,          0.031,           0.124,       0.060,         0.068,     25]],
2330               ["#12",[0.425,   0.125,   0.151,        3,          0.259,          0.034,           0.141,       0.067,         0.077]],
2331               [1/4,  [0.492,   0.144,   0.175,        3,          0.281,          0.036,           0.161,       0.075,         0.087,     30]],
2332               [5/16, [0.615,   0.178,   0.218,        4,          0.350,          0.059,           0.193,       0.084,         0.106]],
2333               [3/8,  [0.740,   0.212,   0.261,        4,          0.389,          0.065,           0.233,       0.094,         0.124]],
2334            ],
2335            htind = drive=="slot" ? 1 : 2,
2336            entry = struct_val(UTS_pan, diam),
2337            dummy=assert(is_def(entry), str("Screw size ",diam," unsupported for head type \"",head,"\"")),
2338            drive_size = drive=="phillips" ? [["drive_size", entry[3]],
2339                                             // ["drive_diameter",INCH*entry[4]],
2340                                             // ["drive_width",INCH*entry[5]],
2341                                              ["drive_depth",INCH*entry[6]]]
2342                                           : [["drive_size", INCH*entry[7]],
2343                                              ["drive_depth",INCH*entry[8]]])
2344           concat([["head","pan round"], ["head_size", INCH*entry[0]], ["head_height", INCH*entry[htind]]], drive_size) 
2345     : head=="button" || head=="round" ? let(
2346            UTS_button = [    // button, hex or torx drive
2347                 //   head diam, height, phillips, hex,   torx, hex depth
2348               ["#0", [0.114,    0.032,   undef,   0.035,  5    , 0.020, 0.015]],
2349               ["#1", [0.139,    0.039,   undef,   3/64,   5    , 0.028, 0.022]],
2350               ["#2", [0.164,    0.046,   undef,   3/64,   6    , 0.028, 0.023]],
2351               ["#3", [0.188,    0.052,   undef,   1/16,   undef, 0.035, undef]],
2352               ["#4", [0.213,    0.059,   undef,   1/16,   8    , 0.035, 0.032]],
2353               ["#5", [0.238,    0.066,   undef,   5/64,   10   , 0.044, 0.038]],
2354               ["#6", [0.262,    0.073,   undef,   5/64,   10   , 0.044, 0.038]],
2355               ["#8", [0.312,    0.087,   undef,   3/32,   15   , 0.052, 0.045]],
2356               ["#10",[0.361,    0.101,   undef,   1/8,    25   , 0.070, 0.052]],
2357               ["#12",[0.413,    0.114,   undef,   1/8,    undef, 0.070, undef]],   // also 0.410, .115, 9/64, hex depth guessed
2358               [1/4,  [0.437,    0.132,   undef,   5/32,   27   , 0.087, 0.068]],
2359               [5/16, [0.547,    0.166,   undef,   3/16,   40   , 0.105, 0.090]],
2360               [3/8,  [0.656,    0.199,   undef,   7/32,   45   , 0.122, 0.106]],
2361               [7/16, [0.750,    0.220,   undef,   1/4,    undef, 0.193, undef]],  // hex depth interpolated
2362               [1/2,  [0.875,    0.265,   undef,   5/16,   55   , 0.175, 0.158]],
2363               [5/8,  [1.000,    0.331,   undef,   3/8,    60   , 0.210, 0.192]],
2364               [3/4,  [1.1,      0.375,   undef,   7/16,   undef, 0.241]],  // hex depth extrapolated
2365             ],
2366             UTS_round = [   // slotted, phillips
2367                  // head diam, head height, phillips drive, hex, torx, ph diam, ph width, ph depth, slot width, slot depth
2368               ["#0", [0.113, 0.053, 0, undef, undef]],
2369               ["#1", [0.138, 0.061, 0, undef, undef]],
2370               ["#2", [0.162, 0.069, 1, undef, undef, 0.100, 0.017, 0.053, 0.031, 0.048]],
2371               ["#3", [0.187, 0.078, 1, undef, undef, 0.109, 0.018, 0.062, 0.035, 0.053]],
2372               ["#4", [0.211, 0.086, 1, undef, undef, 0.118, 0.019, 0.072, 0.039, 0.058]],
2373               ["#5", [0.236, 0.095, 2, undef, undef, 0.154, 0.027, 0.074, 0.043, 0.063]],
2374               ["#6", [0.260, 0.103, 2, undef, undef, 0.162, 0.027, 0.084, 0.048, 0.068]],
2375               ["#8", [0.309, 0.120, 2, undef, undef, 0.178, 0.030, 0.101, 0.054, 0.077]],
2376               ["#10",[0.359, 0.137, 2, undef, undef, 0.195, 0.031, 0.119, 0.060, 0.087]],
2377               ["#12",[0.408, 0.153, 3, undef, undef, 0.249, 0.032, 0.125, 0.067, 0.096]],
2378               [1/4,  [0.472, 0.175, 3, undef, undef, 0.268, 0.034, 0.147, 0.075, 0.109]],
2379               [5/16, [0.590, 0.216, 3, undef, undef, 0.308, 0.040, 0.187, 0.084, 0.132]],
2380               [3/8,  [0.708, 0.256, 4, undef, undef, 0.387, 0.064, 0.228, 0.094, 0.155]],
2381               [1/2,  [0.813, 0.355, 4, undef, undef, 0.416, 0.068, 0.256, 0.106, 0.211]]
2382             ],
2383             entry = struct_val(head=="button" ? UTS_button : UTS_round, diam),
2384             dummy=assert(is_def(entry), str("Screw size ",diam," unsupported for head type \"",head,"\"")),
2385             drive_index = drive=="phillips" ? 2 :
2386                           drive=="hex" ? 3 :
2387                           drive=="torx" ? 4 : undef,
2388             drive_size = drive=="phillips" && head=="round" ? [["drive_size", entry[2]],
2389                                                               // ["drive_diameter",u_mul(INCH,entry[5])],
2390                                                               // ["drive_width",INCH*entry[6]],
2391                                                                ["drive_depth",INCH*entry[7]]]
2392                        : drive=="slot" && head=="round" ?  [["drive_size", INCH*entry[8]],
2393                                                             ["drive_depth",u_mul(INCH,entry[9])]]
2394                        : drive=="hex" && head=="button" ? [["drive_size", INCH*entry[drive_index]],
2395                                                            ["drive_depth", u_mul(INCH,entry[5])]]
2396                        : drive=="torx" && head=="button" ? [["drive_size", entry[drive_index]],
2397                                                             ["drive_depth", u_mul(INCH,entry[6])]]
2398                        : is_def(drive_index) && head=="button" ? [["drive_size", entry[drive_index]]] : []
2399             )
2400             concat([["head",head],["head_size",INCH*entry[0]], ["head_height", INCH*entry[1]]],drive_size) 
2401     : head=="fillister" ? let(
2402             UTS_fillister = [ // head diam, head height, slot width, slot depth, phillips diam, phillips depth, phillips width, phillips #
2403                   ["#0", [0.096, 0.055, 0.023, 0.025, 0.067, 0.039, 0.013, 0]],
2404                   ["#1", [0.118, 0.069, 0.027, 0.031, 0.085, 0.049, 0.015,  ]],
2405                   ["#2", [0.140, 0.083, 0.031, 0.037, 0.104, 0.059, 0.017,  ]],
2406                   ["#3", [0.161, 0.095, 0.035, 0.043, 0.112, 0.068, 0.019, 1]],
2407                   ["#4", [0.183, 0.107, 0.039, 0.048, 0.122, 0.078, 0.019, 1]],
2408                   ["#5", [0.205, 0.120, 0.043, 0.054, 0.143, 0.067, 0.027, 2]],
2409                   ["#6", [0.226, 0.132, 0.048, 0.060, 0.166, 0.091, 0.028, 2]],
2410                   ["#8", [0.270, 0.156, 0.054, 0.071, 0.182, 0.108, 0.030, 2]],
2411                   ["#10",[0.313, 0.180, 0.060, 0.083, 0.199, 0.124, 0.031, 2]],
2412                   ["#12",[0.357, 0.205, 0.067, 0.094, 0.259, 0.141, 0.034, 3]],
2413                   [1/4,  [0.414, 0.237, 0.075, 0.109, 0.281, 0.161, 0.036, 3]],
2414                   [5/16, [0.518, 0.295, 0.084, 0.137, 0.322, 0.203, 0.042, 3]],
2415                   [3/8,  [0.622, 0.355, 0.094, 0.164, 0.389, 0.233, 0.065, 4]],
2416             ],
2417             entry = struct_val(UTS_fillister, diam),
2418             dummy=assert(is_def(entry), str("Screw size ",diam," unsupported for head type \"",head,"\"")),
2419             drive_size = drive=="phillips" ? [["drive_size", entry[7]],
2420                                            //   ["drive_diameter",INCH*entry[4]],
2421                                            //   ["drive_width",INCH*entry[6]],
2422                                               ["drive_depth",INCH*entry[5]]] 
2423                        : drive=="slot"?  [["drive_size", INCH*entry[2]],
2424                                           ["drive_depth",INCH*entry[3]]] : []
2425             )
2426             concat([["head", "fillister"], ["head_size", INCH*entry[0]], ["head_height", INCH*entry[1]]], drive_size) 
2427     : starts_with(head,"flat ") || head=="flat" ? 
2428         let(
2429             headparts = str_split(head," ",keep_nulls=false),
2430             partsok = [for (part=headparts) if (!in_list(part, ["flat","undercut","100","82","small","large","sharp"])) part], 
2431             dummy1=assert(partsok==[], str("Unknown flat head parameter(s) ",partsok)),
2432             dummy2=assert(!(in_list("small",headparts) && in_list("large",headparts)), "Cannot specify large and small flat head at the same time"),
2433             undercut = in_list("undercut", headparts),
2434             small = in_list("small",headparts) || (!in_list("large",headparts) && drive!="hex" && drive!="torx"),
2435             angle = in_list("100", headparts) ? 100 : 82,
2436             dummy3=assert(!undercut || angle==82, "Cannot make undercut 100 degree screw"),
2437             dummy4=assert(small || angle==82, "Only 82 deg large screws are supported"),
2438             dummy5=assert(small || !undercut, "Undercut only supported for small flatheads"),
2439             UTS_flat_small = [  // for phillips drive, slotted, and torx   ASME B18.6.3
2440                    //                     ----- Phillips ----              undercut phillips
2441                    //    ph drive, torx , diam,  depth, width, slotwidth,  diam, depth, width
2442                    //       0       1       2      3      4        5           6        7  
2443                   ["#0", [  0,     undef, 0.062, 0.035, 0.014,   0.023,   0.062, 0.035, 0.014]],
2444                   ["#1", [  0,     undef, 0.070, 0.043, 0.015,   0.026,   0.070, 0.043, 0.015]],
2445                   ["#2", [  1,     6    , 0.096, 0.055, 0.017,   0.031,   0.088, 0.048, 0.017]],
2446                   ["#3", [  1,     undef, 0.100, 0.060, 0.018,   0.035,   0.099, 0.059, 0.018]],
2447                   ["#4", [  1,     8    , 0.122, 0.081, 0.018,   0.039,   0.110, 0.070, 0.018]],
2448                   ["#5", [  2,     undef, 0.148, 0.074, 0.027,   0.043,   0.122, 0.081, 0.018]], //ph#1 for undercut
2449                   ["#6", [  2,     10   , 0.168, 0.094, 0.029,   0.048,   0.140, 0.066, 0.025]],
2450                   ["#8", [  2,     15   , 0.182, 0.110, 0.030,   0.054,   0.168, 0.094, 0.029]],
2451                   ["#10",[  2,     20   , 0.198, 0.124, 0.032,   0.060,   0.182, 0.110, 0.030]],
2452                   ["#12",[  3,     undef, 0.262, 0.144, 0.035,   0.067,   0.226, 0.110, 0.030]],
2453                   [1/4,  [  3,     27   , 0.276, 0.160, 0.036,   0.075,   0.244, 0.124, 0.032]],
2454                   [5/16, [  4,     40   , 0.358, 0.205, 0.061,   0.084,   0.310, 0.157, 0.053]],
2455                   [3/8,  [  4,     40   , 0.386, 0.234, 0.065,   0.094,   0.358, 0.205, 0.061]],
2456                   [1/2,  [  4,     undef, 0.418, 0.265, 0.069,   0.106,   0.402, 0.252, 0.068]]
2457             ],
2458             UTS_flat_small_100 = [  // for phillips drive, slotted, 100 deg angle  ASME B18.6.3
2459                    //                     ----- Phillips ----            
2460                    //    ph drive, torx , diam,  depth, width, slotwidth
2461                    //       0       1       2      3      4        5    
2462                   ["#0", [  0,     undef, 0.054, 0.027, 0.013,   0.023]],
2463                   ["#1", [  0,     undef, 0.062, 0.035, 0.014,   0.026]],
2464                   ["#2", [  1,     6    , 0.088, 0.048, 0.012,   0.031]],
2465                   ["#3", [  1,     undef, 0.096, 0.055, 0.014,   0.035]],
2466                   ["#4", [  1,     8    , 0.110, 0.070, 0.018,   0.039]],
2467                   ["#6", [  2,     10   , 0.148, 0.074, 0.027,   0.048]],
2468                   ["#8", [  2,     15   , 0.162, 0.090, 0.028,   0.054]],
2469                   ["#10",[  2,     20   , 0.178, 0.104, 0.030,   0.060]],
2470                   [1/4,  [  3,     27   , 0.240, 0.124, 0.033,   0.075]],
2471                   [5/16, [  4,     40   , 0.310, 0.157, 0.053,   0.084]],
2472                   [3/8,  [  4,     40   , 0.336, 0.182, 0.056,   0.094]],
2473             ],
2474             UTS_flat_large = [   // for hex drive, torx     ASME B18.3
2475                       // minimum
2476                       // head diam, hex drive size, torx size, hex depth, torx depth
2477                   ["#0", [ 0.117,   1/32,            3    ,     0.025,    0.016]],
2478                   ["#1", [ 0.143,   3/64,            6    ,     0.031,    0.036]],
2479                   ["#2", [ 0.168,   3/64,            6    ,     0.038,    0.036]],
2480                   ["#3", [ 0.193,   1/16,            8    ,     0.044,    0.041]],
2481                   ["#4", [ 0.218,   1/16,            10   ,     0.055,    0.038]],
2482                   ["#5", [ 0.240,   5/64,            10   ,     0.061,    0.038]],
2483                   ["#6", [ 0.263,   5/64,            15   ,     0.066,    0.045]],
2484                   ["#8", [ 0.311,   3/32,            20   ,     0.076,    0.053]],
2485                   ["#10",[ 0.359,    1/8,            25   ,     0.087,    0.061]],
2486                   [1/4,  [ 0.480,   5/32,            30   ,     0.111,    0.075]],
2487                   [5/16, [ 0.600,   3/16,            40   ,     0.135,    0.090]],
2488                   [3/8,  [ 0.720,   7/32,            45   ,     0.159,    0.106]],
2489                   [7/16, [ 0.781,    1/4,            50   ,     0.172,    0.120]],
2490                   [1/2,  [ 0.872,   5/16,            50   ,     0.220,    0.120]],
2491                   [5/8,  [ 1.112,    3/8,            55   ,     0.220,    0.158]],
2492                   [3/4,  [ 1.355,    1/2,            60   ,     0.248,    0.192]],
2493                   [7/8,  [ 1.604,   9/16,            undef,     0.297,    undef]],
2494                   [1,    [ 1.841,    5/8,            undef,     0.325,    undef]],
2495                   [1.125,[ 2.079,    3/4,            undef,     0.358,    undef]],
2496                   [1.25, [ 2.316,    7/8,            undef,     0.402,    undef]],
2497                   [1.375,[ 2.688,    7/8,            undef,     0.402,    undef]],
2498                   [1.5,  [ 2.938,      1,            undef,     0.435,    undef]],
2499             ],
2500             entry = struct_val(    angle==100 ? UTS_flat_small_100 
2501                                  : small ? UTS_flat_small 
2502                                  : UTS_flat_large, 
2503                                diam),
2504             dummy=assert(is_def(entry), str("Screw size ",diam," unsupported for head type \"",head,"\"")),
2505             a=[1.92+1.82, 1.88+1.8, 1.88+1.8]/2,
2506             b=[.003+.013, .063+.073, .125+.135]/2,
2507             smallsize = a[diamgroup]*diameter-b[diamgroup],
2508     
2509             csmall=[2.04, 2, 2],
2510             dsmall=[.003, .063, .125], 
2511             dlarge = [-.031, .031, .062],
2512             sharpsize = small ? csmall[diamgroup]*diameter-dsmall[diamgroup] // max theoretical (sharp) head diam
2513                                     : diameter < 0.1 ? [0.138,0.168,0.0822,0.0949][(diameter - 0.06)/.013] 
2514                                     : 2*diameter-dlarge[diamgroup],
2515             largesize = lerp(entry[0],sharpsize,.20),   // Have min size and max theory size.  Use point 20% up from min size
2516             undercut_height = let(
2517                                   a=[.432+.386, .417+.37, .417+.37]/2,
2518                                   b=[.001+.005, .026+.029, .052+.055]/2
2519                               )
2520                               a[diamgroup]*diameter + b[diamgroup],
2521             e=undercut ? [.202+.134, .192+.129, .192+.129]/2 
2522              : angle==100 ? [.222+.184]/2 
2523              : [.288+.192, .274+.184, .274+.184]/2,
2524             f=undercut ? [.002, .012+.011, .024+.019]/2
2525              : angle==100 ? [.0005+.004]/2 
2526              : [.004, .015+.017, .034+.027],
2527             tipdepth_small = e[diamgroup]*diameter + f[diamgroup],
2528             driveind = small && drive=="phillips" ? 0
2529                      : !small && drive=="hex" ? 1 
2530                      : drive=="torx" ? 2 
2531                      : undef,
2532             drive_dims = small ? (
2533                            drive=="phillips" && !undercut ? [
2534                                                            //  ["drive_diameter",INCH*entry[2]],
2535                                                            //  ["drive_width",INCH*entry[4]],
2536                                                              ["drive_depth",INCH*entry[3]]
2537                                                             ]
2538                          : drive=="phillips" && undercut ?  [
2539                                                             // ["drive_diameter",INCH*entry[6]],
2540                                                             // ["drive_width",INCH*entry[8]],
2541                                                              ["drive_depth",INCH*entry[7]]
2542                                                             ] 
2543                          : drive=="slot" ? [["drive_size", INCH*entry[5]], 
2544                                             ["drive_depth", INCH*tipdepth_small]] :
2545                            
2546                            []
2547                            )
2548                         :
2549                           (
2550                             drive=="hex" ? [["drive_depth", INCH*entry[3]]] :
2551                             drive=="torx" ? [["drive_depth", INCH*entry[4]]] : []
2552                           )
2553         )
2554         [
2555           ["head","flat"],
2556           ["head_angle",angle],
2557           ["head_size", in_list("sharp",headparts) ? sharpsize*INCH
2558                        : small ? smallsize*INCH : largesize*INCH], //entry[0]*INCH],
2559           ["head_size_sharp", sharpsize*INCH],
2560           if (is_def(driveind)) ["drive_size", (drive=="hex"?INCH:1)*entry[driveind]],
2561           if (undercut) ["head_height", undercut_height*INCH],
2562           each drive_dims
2563         ]
2564     : []
2565 )
2566 concat([
2567           ["type","screw_info"],
2568           ["system","UTS"],
2569           ["diameter",INCH*diameter],
2570           ["pitch", pitch],
2571           ["drive",drive]
2572         ],
2573         head_data
2574 );
2575
2576
2577function _screw_info_metric(diam, pitch, head, thread, drive) =
2578 let(
2579   pitch =
2580     is_num(thread) ? thread :
2581     is_def(pitch) ? pitch :
2582     let(
2583        tind=struct_val([["coarse",0],
2584                         ["fine",1],
2585                         ["extra fine",2],["extrafine",2],
2586             ["super fine",3],["superfine",3]],
2587                         downcase(thread)),
2588        dummy = assert(is_def(tind), str("Unknown thread type, \"",thread,"\"")),
2589                            // coarse  fine  xfine superfine
2590        ISO_thread = [
2591                      [1  , [0.25,    0.2 ,   undef, undef,]],
2592                      [1.2, [0.25,    0.2 ,   undef, undef,]],
2593                      [1.4, [0.3 ,    0.2 ,   undef, undef,]],
2594                      [1.6, [0.35,    0.2 ,   undef, undef,]],
2595                      [1.7, [0.35,   undef,   undef, undef,]],
2596                      [1.8, [0.35,    0.2 ,   undef, undef,]],
2597                      [2  , [0.4 ,    0.25,   undef, undef,]],
2598                      [2.2, [0.45,    0.25,   undef, undef,]],
2599                      [2.3, [0.4 ,   undef,   undef, undef,]],
2600                      [2.5, [0.45,    0.35,   undef, undef,]],
2601                      [2.6, [0.45,   undef,   undef, undef,]],
2602                      [3  , [0.5 ,    0.35,   undef, undef,]],
2603                      [3.5, [0.6 ,    0.35,   undef, undef,]],
2604                      [4  , [0.7 ,    0.5 ,   undef, undef,]],
2605                      [5  , [0.8 ,    0.5 ,   undef, undef,]],
2606                      [6  , [1   ,    0.75,   undef, undef,]],
2607                      [7  , [1   ,    0.75,   undef, undef,]],
2608                      [8  , [1.25,    1   ,    0.75, undef,]],
2609                      [9  , [1.25,    1   ,    0.75, undef,]],
2610                      [10 , [1.5 ,    1.25,    1   ,  0.75,]],
2611                      [11 , [1.5 ,    1   ,    0.75, undef,]],
2612                      [12 , [1.75,    1.5 ,    1.25,  1,   ]],
2613                      [14 , [2   ,    1.5 ,    1.25,  1,   ]],
2614                      [16 , [2   ,    1.5 ,    1   , undef,]],
2615                      [18 , [2.5 ,    2   ,    1.5 ,  1,   ]],
2616                      [20 , [2.5 ,    2   ,    1.5 ,  1,   ]],
2617                      [22 , [2.5 ,    2   ,    1.5 ,  1,]],
2618                      [24 , [3   ,    2   ,    1.5 ,  1,]],
2619                      [27 , [3   ,    2   ,    1.5 ,  1,]],
2620                      [30 , [3.5 ,    3   ,    2   ,  1.5,]],
2621                      [33 , [3.5 ,    3   ,    2   ,  1.5,]],
2622                      [36 , [4   ,    3   ,    2   ,  1.5,]],
2623                      [39 , [4   ,    3   ,    2   ,  1.5,]],
2624                      [42 , [4.5 ,    4   ,    3   ,  2,]],
2625                      [45 , [4.5 ,    4   ,    3   ,  2,]],
2626                      [48 , [5   ,    4   ,    3   ,  2,]],
2627                      [52 , [5   ,    4   ,    3   ,  2,]],
2628                      [56 , [5.5 ,    4   ,    3   ,  2,]],
2629                      [60 , [5.5 ,    4   ,    3   ,  2,]],
2630                      [64 , [6   ,    4   ,    3   ,  2,]],
2631                      [68 , [6   ,    4   ,    3   ,  2,]],
2632                      [72 , [6   ,    4   ,    3   ,  2,]],
2633                      [80 , [6   ,    4   ,    3   ,  2,]],
2634                      [90 , [6   ,    4   ,    3   ,  2,]],
2635                      [100, [6   ,    4   ,    3   ,  2,]],
2636        ],
2637        tentry = struct_val(ISO_thread, diam)
2638     )
2639     assert(is_def(tentry), str("Unknown screw size, M",diam))
2640     assert(is_def(tentry[tind]), str("No ",thread," pitch known for M",diam))
2641     tentry[tind],
2642   
2643   head_data =
2644       head=="none" ? let(
2645           metric_setscrew =
2646               [
2647                  //   hex    torx, torx depth, slot width, slot depth 
2648                [1.2, [undef, undef,   undef,    0.330,        0.460]],
2649                [1.4, [0.7,   undef,   undef,    undef,        undef]],
2650                [1.6, [0.7,   undef,   undef,    0.380,        0.650]],
2651                [1.8, [0.7,   undef,   undef,    undef,        undef]],
2652                [2,   [0.9,   undef,   undef,    0.380,        0.740]],
2653                [2.5, [1.3,   undef,   undef,    0.530,        0.835]],
2654                [3,   [1.5,     6,     0.77,     0.530,        0.925]],
2655                [3.5, [undef, undef,   undef,    0.630,        1.085]],
2656                [4,   [2,       8,     1.05,     0.730,        1.270]],
2657                [5,   [2.5,    10,     1.24,     0.930,        1.455]],
2658                [6,   [3,      15,     1.74,     1.130,        1.800]],
2659                [8,   [4,      25,     2.24,     1.385,        2.250]],
2660                [10,  [5,      40,     2.97,     1.785,        2.700]],
2661                [12,  [6,      45,     3.48,     2.185,        3.200]],
2662                [16,  [8,      55,     5.15]],
2663                [20,  [10,   undef,    undef]],    
2664               ],
2665            entry = struct_val(metric_setscrew, diam),
2666            dummy=assert(drive=="none" || is_undef(drive) || is_def(entry), str("Screw size M",diam," unsupported for headless screws")),
2667            drive_dim = drive=="hex" ? [["drive_size", entry[0]], ["drive_depth", diam/2]]
2668                      : drive=="torx" ? [["drive_size", entry[1]], ["drive_depth", entry[2]]]
2669                      : drive=="slot" ? [["drive_size", entry[3]], ["drive_depth", entry[4]]]
2670                      : []
2671           )
2672           concat([["head","none"]], drive_dim) 
2673     : head=="hex" ? let(
2674            metric_hex = [
2675              // flat to flat width, height
2676              [5, [8, 3.5]],
2677              [6, [10,4]],
2678              [8, [13, 5.3]],
2679              [10, [17, 6.4]],
2680              [12, [19, 7.5]],
2681              [14, [22, 8.8]],
2682              [16, [24, 10]],
2683              [18, [27,11.5]],
2684              [20, [30, 12.5]],
2685              [24, [36, 15]],
2686              [30, [46, 18.7]],
2687            ],
2688            entry = struct_val(metric_hex, diam)
2689           )
2690           assert(is_def(entry), str("Screw size M",diam," unsupported for head type \"",head,"\""))
2691           [["head", "hex"], ["head_size", entry[0]], ["head_height", entry[1]]] 
2692     : in_list(head,["socket","socket ribbed"]) ? let(
2693            // ISO 14579 gives dimensions for Torx (hexalobular) socket heads
2694            metric_socket = [    // height = screw diameter
2695                      //diam, hex, torx size, torx depth
2696                [1.4, [2.5,   1.3]],
2697                [1.6, [3,     1.5]],
2698                [2,   [3.8,   1.5,    6,        0.775]],
2699                [2.5, [4.5,     2,    8,        0.975]],
2700                [2.6, [5,       2,    8,        1.05]],
2701                [3,   [5.5,   2.5,    10,       1.14]],
2702                [3.5, [6.2,   2.5]]   ,
2703                [4,   [7,       3,    25,       1.61]],
2704                [5,   [8.5,     4,    27,       1.84]],
2705                [6,   [10,      5,    30,       2.22]],
2706                [7,   [12,      6]],
2707                [8,   [13,      6,    45,       3.115]],
2708                [10,  [16,      8,    50,       3.82]],
2709                [12,  [18,     10,    55,       5.015]],
2710                [14,  [21,     12,    60,       5.805]],
2711                [16,  [24,     14,    70,       6.815]],
2712                [18,  [27,     14,    80,       7.75]],
2713                [20,  [30,     17,    90,       8.945]],
2714                [22,  [33,     17]],
2715                [24,  [36,     19,    100,     10.79]],
2716                [27,  [40,     19]],
2717                [30,  [45,     22]],
2718                [33,  [50,     24]],
2719                [36,  [54,     27]],
2720                [42,  [63,     32]],
2721                [48,  [72,     36]],
2722            ],
2723            entry = struct_val(metric_socket, diam),
2724            dummy=assert(is_def(entry), str("Screw size M",diam," unsupported for head type \"",head,"\"")),
2725            drive_size =  drive=="hex" ? [["drive_size",entry[1]],["drive_depth",diam/2]] :
2726                          drive=="torx" ? [["drive_size", entry[2]], ["drive_depth", entry[3]]] :
2727                          []
2728            )
2729            concat([["head",head],["head_size",entry[0]], ["head_height", diam]],drive_size) 
2730     : in_list(head,["pan","pan round","pan flat"]) ? let (
2731           metric_pan = [  // pan head for phillips or slotted, torx from ISO 14583
2732                      //          head height
2733                      // diam, slotted  phillips phillips size  phillips diam, phillips depth, ph width, slot width,slot depth, torx size, torx depth
2734                 [1.6,   [3.2,   1  ,     1.3,        0,          undef,         undef,        undef,       0.4,      0.35]],
2735                 [2,     [4,     1.3,     1.6,        1,          1.82,          1.19,         0.48,        0.5,      0.5,        6,         0.7]],
2736                 [2.5,   [5,     1.5,     2,          1,          2.68,          1.53,         0.70,        0.6,      0.6,        8,         0.975]],
2737                 [3,     [5.6,   1.8,     2.4,        1,          2.90,          1.76,         0.74,        0.8,      0.7,        10,        1.14]],
2738                 [3.5,   [7,     2.1,     3.1,        2,          3.92,          1.95,         0.87,        1.0,      0.8,        15,        1.2]],
2739                 [4,     [8,     2.4 ,    3.1,        2,          4.40,          2.45,         0.93,        1.2,      1.0,        20,        1.465]],
2740                 [5,     [9.5,   3,       3.8,        2,          4.90,          2.95,         1.00,        1.2,      1.2,        25,        1.715]],
2741                 [6,     [12,    3.6,     4.6,        3,          6.92,          3.81,         1.14,        1.6,      1.4,        30,        2.22]],
2742                 [8,     [16,    4.8,     6,          4,          9.02,          4.88,         1.69,        2.0,      1.9,        45,        2.985]],
2743                 [10,    [20,    6.0,     7.5,        4,          10.18,         5.09,         1.84,        2.5,      2.4,        50,        3.82]], 
2744            ],
2745            type = head=="pan" ? (drive=="slot" ? "pan flat" : "pan round") : head,
2746            htind = drive=="slot" ? 1 : 2,
2747            entry = struct_val(metric_pan, diam),
2748            dummy=assert(is_def(entry), str("Screw size M",diam," unsupported for head type \"",head,"\"")),
2749            drive_size = drive=="phillips" ? [["drive_size", entry[3]],
2750                                              //["drive_diameter", entry[4]],
2751                                              ["drive_depth",entry[5]],
2752                                              //["drive_width",entry[6]]
2753                                             ] 
2754                       : drive=="torx" ? [["drive_size", entry[9]], ["drive_depth", entry[10]]]
2755                       : drive=="slot" ? [["drive_size", entry[7]], ["drive_depth", entry[8]]] 
2756                       : []
2757           )
2758           concat([["head",type], ["head_size", entry[0]], ["head_height", entry[htind]]], drive_size) 
2759     : head=="button" || head=="cheese" ? let(
2760            // hex drive depth from ISO 7380-1
2761            metric_button = [    // button, hex drive
2762                 //   head diam, height, hex, phillips, hex drive depth, torx size, torx depth
2763                 [1.6, [2.9,     0.8,    0.9, undef,    0.55]], // These four cases,
2764                 [2,   [3.5,     1.3,    1.3, undef,    0.69]], // extrapolated hex depth
2765                 [2.2, [3.8,     0.9,    1.3, undef,    0.76]], //
2766                 [2.5, [4.6,     1.5,    1.5, undef,    0.87]], //
2767                 [3,   [5.7,     1.65,   2,   undef,    1.04,                8,      0.81]],
2768                 [3.5, [5.7,     1.65,   2,   undef,    1.21]], // interpolated hex depth
2769                 [4,   [7.6,     2.2,    2.5, undef,    1.30,                15,     1.3]],
2770                 [5,   [9.5,     2.75,   3,   undef,    1.56,                25,     1.56]],
2771                 [6,   [10.5,    3.3,    4,   undef,    2.08,                27,     2.08]],
2772                 [8,   [14,      4.4,    5,   undef,    2.60,                40,     2.3]],
2773                 [10,  [17.5,    5.5,    6,   undef,    3.12,                45,     2.69]],
2774                 [12,  [21,      6.6,    8,   undef,    4.16,                55,     4.02]],    
2775                 [16,  [28,      8.8,    10,  undef,    5.2]], 
2776             ],
2777             metric_cheese = [   // slotted, phillips     ISO 1207, ISO 7048
2778                                 // hex drive is not supported (hence undefs)
2779                // head diam, head height, hex drive, phillips drive, slot width, slot depth, ph diam
2780                [1,   [2,     0.7,         undef,      undef]],
2781                [1.2, [2.3,   0.8,         undef,      undef]],
2782                [1.4, [2.6,   0.9,         undef,      undef]],
2783                [1.6, [3,     1,           undef,      undef,         0.4,        0.45]],
2784                [2,   [3.8,   1.3,         undef,      1    ,         0.5,        0.6,        undef,       undef]],
2785                [2.5, [4.5,   1.6,         undef,      1    ,         0.6,        0.7,          2.7,        1.20]],
2786                [3,   [5.5,   2,           undef,      2    ,         0.8,        0.85,         3.5,        0.86]],
2787                [3.5, [6,     2.4,         undef,      2    ,         1.0,        1.0,          3.8,        1.15]],
2788                [4,   [7,     2.6,         undef,      2    ,         1.2,        1.1,          4.1,        1.45]],
2789                [5,   [8.5,   3.3,         undef,      2    ,         1.2,        1.3,          4.8,        2.14]],
2790                [6,   [10,    3.9,         undef,      3    ,         1.6,        1.6,          6.2,        2.25]],
2791                [8,   [13,    5,           undef,      3    ,         2.0,        2.0,          7.7,        3.73]],
2792                [10,  [16,    6,           undef,      undef,         2.5,        2.4,        undef,       undef]]
2793             ],
2794             metric_cheese_torx = [ // torx cheese, ISO 14580, the heads are taller than other cheese screws
2795                      //head diam, head height, torx size, torx depth
2796                [2,   [3.8,        1.55,         6,         0.775]],
2797                [2.5, [4.5,        1.85,         8,         0.845]],
2798                [3,   [5.5,        2.4,         10,         1.14]],
2799                [3.5, [6,          2.6,         15,         1.2]],
2800                [4,   [7,          3.1,         20,         1.465]],
2801                [5,   [8.5,        3.65,        25,         1.715]],
2802                [6,   [10,         4.4,         30,         2.095]],
2803                [8,   [13,         5.8,         45,         2.855]],
2804                [10,  [16,         6.9,         59,         3.235]]
2805             ],
2806
2807             entry = struct_val( head=="button" ? metric_button 
2808                               : drive=="torx"? metric_cheese_torx 
2809                               : metric_cheese, 
2810                            diam),
2811             dummy=assert(is_def(entry), str("Screw size M",diam," unsupported for head type \"",head,"\"")),
2812             drive_index = drive=="phillips" ? 3 
2813                         : drive=="hex" ? 2 
2814                         : undef,
2815             drive_dim = head=="button" && drive=="hex" ? [["drive_depth", entry[4]]] 
2816                       : head=="button" && drive=="torx" ? [["drive_size", entry[5]],["drive_depth", entry[6]]] 
2817                       : head=="cheese" && drive=="torx" ? [["drive_size", entry[2]],["drive_depth", entry[3]]] 
2818                       : head=="cheese" && drive=="slot" ? [["drive_size", entry[4]], ["drive_depth", entry[5]]] 
2819                       : head=="cheese" && drive=="phillips" ? [
2820                                                                //["drive_diameter", entry[6]],
2821                                                                ["drive_depth", entry[7]],
2822                                                                //["drive_width", entry[6]/4]  // Fabricated this width value to fill in missing field
2823                                                               ]  
2824                       :[],
2825             drive_size = is_def(drive_index) ? [["drive_size", entry[drive_index]]] : []
2826             )
2827             concat([["head",head],["head_size",entry[0]], ["head_height", entry[1]]],drive_size, drive_dim) 
2828     : starts_with(head,"flat ") || head=="flat" ?
2829         let(
2830             headparts = str_split(head," ",keep_nulls=false),
2831             partsok = [for (part=headparts) if (!in_list(part, ["flat","small","large","sharp","90"])) part], 
2832             dummy1=assert(partsok==[], str("Unknown flat head parameter(s) ",partsok)),
2833             dummy2=assert(!(in_list("small",headparts) && in_list("large",headparts)), "Cannot specify large and small flat head at the same time"),
2834             small = in_list("small",headparts) || (!in_list("large",headparts) && drive!="hex"),
2835             metric_flat_large = [ // for hex drive from ISO-10642, don't know where torx came from
2836                     // -- diam -----   hex size    hex depth     torx   torx depth
2837                     // theory  actual
2838                     //  max     min
2839                  [3,  [6.72,     5.54,      2  ,       1.1,        10,   0.96]],
2840                  [4,  [8.96,     7.53,      2.5,       1.5,        20,   1.34]],
2841                  [5,  [11.20,    9.43,      3  ,       1.9,        25,   1.54]],
2842                  [6,  [13.44,    11.34,     4  ,       2.2,        30,   1.91]],
2843                  [8,  [17.92,    15.24,     5  ,       3.0,        40,   2.3]],
2844                  [10, [22.4,     19.22,     6  ,       3.6,        50,   3.04]],
2845                  [12, [26.88,    23.12,     8  ,       4.3]], 
2846                  [14, [30.8,     26.52,    10  ,       4.5]],
2847                  [16, [33.6,     29.01,    10  ,       4.8]],
2848                  [20, [40.32,    36.05,    12  ,       5.6]]    
2849             ],
2850             metric_flat_small = [ // Phillips from ISO 7046
2851                                   // Slots from ISO 2009
2852                                   // Torx from ISO 14581
2853                    // theory    mean                                             nominal       mean             torx
2854                    //  diam, actual diam  ph size, ph diam, ph depth, ph width, slot width, slot depth  torx   mean depth
2855                 [1.6, [ 3.6,    2.85,         0,     1.6,    0.75,    undef,     0.4,         0.41,     undef,  undef  ]],
2856                 [2,   [ 4.4,    3.65,         0,     1.9,    1.05,     0.53,     0.5,         0.5,         6,    0.575 ]],
2857                 [2.5, [ 5.5,    4.55,         1,     2.9,    1.6,      0.74,     0.6,         0.625,       8,    0.725 ]],
2858                 [3,   [ 6.3,    5.35,         1,     3.2,    1.90,     0.79,     0.8,         0.725,      10,    0.765 ]],
2859                 [3.5, [ 8.2,    7.12,         2,     4.4,    2.15,     0.91,     1.0,         1.05,       15,    1.240 ]],
2860                 [4,   [ 9.4,    8.22,         2,     4.6,    2.35,     0.96,     1.2,         1.15,       10,    1.335 ]],
2861                 [5,   [10.4,    9.12,         2,     5.2,    2.95,     1.04,     1.2,         1.25,       25,    1.315 ]],
2862                 [6,   [12.6,   11.085,        3,     6.8,    3.25,     1.12,     1.6,         1.4,        30,    1.585 ]],
2863                 [8,   [17.3,   15.585,        4,     8.9,    4.30,     1.80,     2.0,         2.05,       45,    2.345 ]],
2864                 [10,  [20  ,   18.04,         4,    10.0,    5.40,    undef,     2.5,         2.3,        50,    2.605 ]],
2865                 [12,  [24  ,   21.75 ]],  // Additional screw head data from ISO 7721, but no driver data   
2866                 [14,  [28  ,   25.25 ]],
2867                 [16,  [32  ,   28.75 ]],
2868                 [18,  [36  ,   32.2  ]],
2869                 [20,  [40  ,   35.7  ]]
2870             ],
2871             entry = struct_val(small ? metric_flat_small : metric_flat_large, diam),
2872             dummy=assert(is_def(entry), str("Screw size M",diam," unsupported for head type \"",head,"\"")),
2873             driveind = small && drive=="phillips" ? 2
2874                      : !small && drive=="hex" ? 2
2875                      : !small && drive=="torx" ? 4
2876                      : small && drive=="torx" ? 8 : undef,
2877             drive_dim = small && drive=="phillips" ? [
2878                                                      // ["drive_diameter", entry[3]],
2879                                                       ["drive_depth",entry[4]],
2880                                                      // ["drive_width", entry[5]]
2881                                                      ] 
2882                       : small && drive=="slot" ? [["drive_size", entry[6]], ["drive_depth", entry[7]]] 
2883                       : drive=="torx" ? [["drive_depth", entry[driveind+1]]] 
2884                       : !small && drive=="hex" ? [["drive_depth", entry[3]]]
2885                       : [],
2886             sharpsize = entry[0]
2887         )
2888         [
2889           ["head","flat"],
2890           ["head_angle",90],
2891           ["head_size", in_list("sharp",headparts) ? sharpsize
2892                       : small ? entry[1]              // entry is mean diameter
2893                       : lerp(entry[1],entry[0],.2)],  // entry is min diameter, so enlarge it 20%
2894           ["head_size_sharp", sharpsize],
2895           if (is_def(driveind)) ["drive_size", entry[driveind]],
2896           each drive_dim
2897         ]
2898     : [] 
2899 )
2900 concat(
2901        [
2902          ["type","screw_info"],
2903          ["system","ISO"],
2904          ["diameter",diam],
2905          ["pitch", pitch],
2906          ["drive",drive]
2907        ],
2908        head_data
2909 );
2910
2911function _is_positive(x) = is_num(x) && x>0;
2912
2913
2914function _validate_nut_spec(spec) =
2915   let(
2916       //dummy=echo_struct(spec,"Screw Specification"),
2917       systemOK = in_list(struct_val(spec,"system"), ["UTS","ISO"]),
2918       diamOK = _is_positive(struct_val(spec, "diameter")),
2919       pitch = struct_val(spec,"pitch"),
2920       pitchOK = is_undef(pitch) || (is_num(pitch) && pitch>=0),
2921       shape = struct_val(spec, "shape"),
2922       shapeOK = shape=="hex" || shape=="square",
2923       thicknessOK = _is_positive(struct_val(spec, "thickness")),
2924       widthOK = _is_positive(struct_val(spec, "width"))
2925    )
2926    assert(systemOK, str("Nut spec has invalid \"system\", ", struct_val(spec,"system"), ".  Must be \"ISO\" or \"UTS\""))
2927    assert(diamOK, str("Nut spec has invalid \"diameter\", ", struct_val(spec,"diameter")))
2928    assert(pitchOK, str("Nut spec has invalid \"pitch\", ", pitch))
2929    assert(shapeOK, str("Nut spec has invalid \"shape\", ", shape, ".  Must be \"square\" or \"hex\""))
2930    assert(thicknessOK, str("Nut spec thickness is not a postive number: ",struct_val(spec,"thickness")))
2931    assert(widthOK, str("Nut spec width is not a postive number: ",struct_val(spec,"width")))
2932    spec;
2933
2934    
2935function _validate_screw_spec(spec) =
2936    let(
2937        //dummy=echo_struct(spec,"Screw Specification"),
2938        systemOK = in_list(struct_val(spec,"system"), ["UTS","ISO"]),
2939        diamOK = _is_positive(struct_val(spec, "diameter")),
2940        pitch = struct_val(spec,"pitch"),
2941        pitchOK = is_undef(pitch) || (is_num(pitch) && pitch>=0),
2942        head = struct_val(spec,"head"),
2943        headOK = head=="none" || 
2944                    (in_list(head, ["cheese","pan flat","pan round", "flat", "button","socket","socket ribbed", "fillister","round","hex"]) &&
2945                     _is_positive(struct_val(spec, "head_size"))),
2946        flatheadOK = (head!="flat" || _is_positive(struct_val(spec,"head_size_sharp"))),
2947        drive = struct_val(spec, "drive"),
2948        driveOK = is_undef(drive) || drive=="none"
2949                  || (_is_positive(struct_val(spec, "drive_depth")) && _is_positive(struct_val(spec, "drive_size")))
2950    )
2951    assert(systemOK, str("Screw spec has invalid \"system\", ", struct_val(spec,"system"), ".  Must be \"ISO\" or \"UTS\""))
2952    assert(diamOK, str("Screw spec has invalid \"diameter\", ", struct_val(spec,"diameter")))
2953    assert(pitchOK, str("Screw spec has invalid \"pitch\", ", pitch))
2954    assert(headOK, "Screw head type invalid or unknown for your screw type and size")  // head is "undef" for invalid heads; we don't know what the user specified
2955    assert(flatheadOK, "Flat head screw invalid because no \"head_size_sharp\" value is present.")
2956    assert(driveOK, str("Screw drive type \"",drive,"\" invalid or unknown for your screw size or head type, \"",head,"\""))
2957    spec;
2958
2959
2960
2961// Function: thread_specification()
2962// Synopsis: Returns the thread geometry for a given screw.
2963// Topics: Threading, Screws
2964// See Also: screw(), screw_hole()
2965// Usage:
2966//   thread_specification(screw_spec, [tolerance], [internal])
2967// Description:
2968//   Determines actual thread geometry for a given screw with specified tolerance and nominal size.  See [tolerance](#subsection-tolerance) for
2969//   information on tolerances.  If tolerance is omitted the default is used.  If tolerance
2970//   is "none" or 0 then return the nominal thread geometry.  When `internal=true` the nut tolerance is used.  
2971//   .
2972//   The return value is a structure with the following fields:
2973//   - pitch: the thread pitch
2974//   - d_major: major diameter range
2975//   - d_pitch: pitch diameter range
2976//   - d_minor: minor diameter range
2977//   - basic: vector `[minor, pitch, major]` of the nominal or "basic" diameters for the threads
2978// Arguments:
2979//   screw_spec = screw specification structure
2980//   tolerance = thread geometry tolerance.  Default: For ISO, "6g" for screws, "6H" for internal threading (nuts).  For UTS, "2A" for screws, "2B" for internal threading (nuts).
2981//   internal = true for internal threads.  Default: false
2982function thread_specification(screw_spec, tolerance=undef, internal=false) =
2983  let( 
2984       diam = _nominal_diam(screw_spec),
2985       pitch = struct_val(screw_spec, "pitch"),
2986       tspec = tolerance == 0 || tolerance=="none" ? _exact_thread_tolerance(diam, pitch)
2987             :  struct_val(screw_spec,"system") == "ISO" ? _ISO_thread_tolerance(diam, pitch, internal, tolerance)
2988             :  struct_val(screw_spec,"system") == "UTS" ? _UTS_thread_tolerance(diam, pitch, internal, tolerance)
2989             :  assert(false,"Unknown screw system ",struct_val(screw_spec,"system"))
2990  )
2991  assert(min(struct_val(tspec,"d_minor"))>0, "Thread specification is too coarse for the diameter")
2992  tspec;
2993
2994
2995
2996
2997
2998// recess sizing:
2999// http://www.fasnetdirect.com/refguide/Machinepancombo.pdf
3000//
3001/*   ASME B 18.6.3
3002http://www.smithfast.com/newproducts/screws/msflathead/
3003
3004
3005/* phillips recess diagram
3006
3007http://files.engineering.com/getfile.aspx?folder=76fb0d5e-1fff-4c49-87a5-05979477ca88&file=Noname.jpg&__hstc=212727627.6c577ef84c12d9cc69c819eea7be49d2.1563972499721.1563972499721.1563972499721.1&__hssc=212727627.1.1563972499721&__hsfp=165344926
3008
3009*/
3010
3011
3012//
3013// https://www.bayoucitybolt.com/socket-head-cap-screws-metric.html
3014//
3015// Torx drive depth for UTS and ISO (at least missing for "flat small", which means you can't select torx for this head type)
3016// Handle generic phillips (e.g. ph2) or remove it?
3017
3018// https://www.fasteners.eu/tech-info/ISO/7721-2/
3019//
3020//    JIS 
3021//https://www.garagejournal.com/forum/media/jis-b-4633-vs-iso-8764-1-din-5260-ph.84492/
3022
3023//square:
3024//https://www.aspenfasteners.com/content/pdf/square_drive_specification.pdf
3025//http://www.globalfastener.com/standards/index.php?narr58=149
3026//https://patents.google.com/patent/US1003657
3027
3028// thread standards:
3029// https://www.gewinde-normen.de/en/index.html
3030
3031/////////////////////////////////////////////////////////////////////////////////////////*
3032/////////////////////////////////////////////////////////////////////////////////////////*
3033/////////////////////////////////////////////////////////////////////////////////////////*
3034///  
3035///  TODO list:
3036///  
3037///  need to make holes at actual size instead of nominal?
3038///     or relative to actual size?
3039///     That means I need to preserve thread= to specify this
3040///  torx depth for UTS pan head
3041///  $fn control
3042///  phillips driver spec with ph# is confusing since it still looks up depth in tables
3043///     and can give an error if it's not found
3044///  torx depths missing for pan head
3045///  support for square drive?  (It's in the ASME standard)
3046///  
3047/////////////////////////////////////////////////////////////////////////////////////////*
3048/////////////////////////////////////////////////////////////////////////////////////////*
3049/////////////////////////////////////////////////////////////////////////////////////////*
3050
3051// vim: expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap
3052